06 - Working with strings in PHP

In PHP, when we use pieces of text, it is called string. It is one of the  data types in PHP. String may contain letters, numbers, punctuations, spaces, tabs or any other type of character. In PHP strings are enclosed in double quotes or in single quotes.

Example

<html>
<head>
    <title> My PHP page</title>
</head>
<body>
    <?php
    echo 'I like to use PHP scripting language.';
    echo 'PHP language';
    echo 'version is PHP 5';
    echo '"We are learning PHP,” they told"';
    ?>
</body>
</html>

The output of above program is:

In PHP string literal can be of following types:

  1. Single quoted strings
  2. Double quoted strings
  3. Heredoc syntax
  4. Nowdoc syntax

Double quoted strings:

In PHP with double quoted strings following escape sequences are used:

Escape characters

Escape sequence

Meaning

\n

Newline character

\r

carriage return character

\t

Tab horizontal

\v

Tab Vertical

\e

Escape

\f

Form feed

\\

Escape backslash

\$

dollar sign

\"

Escape double-quote

Heredoc strings

In PHP heredoc strings can be used with <<< operator. After this operator, an Identifier is used EOD and then string follows it. After string the same EOD identifier is used to close it.

It can be used in following way:

<?php
$str = <<<EOD
Introduction of heredoc strings in PHP
EOD;
?>

<?php
class example
{
    var $foo;
    var $lang;
    function example()
    {
        $this->foo = 'Server side scripting';
    }
}
$example = new example();
$name = 'PHP language';
echo <<<EOT
I am using "$name"
$example->foo
EOT;
?>

The output of above code is:


 

In PHP single quotes are not part of the string. They are delimiters. If we have to use single quote inside a string we must enclose it in single quotes, we should use \ before the single quote inside the string. Like

echo 'I\'ll use the PHP with HTML5';

This statement will output as:

I’ll use the PHP with HTML5

Here backslash (\) is used to convey PHP interpreter that single quote (‘) should be treated as a literal single quote instead of the single quote that represents “end of string”, this is called escaping and \ is known as escape character.

Formatted display of Strings in PHP

With the help of format specifiers a string can be displayed in many ways. In other programming languages like C and C++ also the format specifiers are used for the same. Format specifiers begin with % sign and followed by a letter that is used to display the type of variable to be displayed.

In PHP, following specifiers can be used:

Specifiers

Description

%%

To Display a percent sign

%b

To display an integer in binary format

%c

To display a character

%d

To display a signed decimal number

%u

To display an unsigned decimal number

%f

To display a floating-point number

%F

To display a floating-point number

%o

To display an octal  number

%s

To display a String

%x

To display hexadecimal number in lowercase letters

%X

To display hexadecimal number in uppercase letters

How to convert a String into Array in PHP

To convert any string into array in PHP explode() function can be used. The explode() function takes three arguments and returns an array: These three arguments are:

  1. delimiter - the character that is to be used as delimiter between array elements. For example a space character or a comma.
  2. string - the string that is to be converted into an array.
  3. divisions – It Specifies the maximum number of array elements the string should be broken up into.

Example:

<?php
$myLanguage = "I am using PHP scripting language.";
$myArray = explode(" ", $myLanguage);
print_r($myArray);
?>

The output of above code is:

Constructs in PHP

In any programming language the execution flow of a program can be of following types:

1. Sequential

In this type of execution flow the statements of a program are executed in a sequence one after another.

2. Branching

Many times we need to execute the statements of a program after verifying the condition, like if we need to Log in to Google account first of all we have to provide valid authentication details. These details should be verified and if the details are OK we can log in to google account otherwise we will get an error message.

In this type of scenario, we use branching/ conditional or selection constructs to execute the process.

Conditional constructs can be following types:

1. If

The syntax of if construct is:

If (expression)
{
//if the expression is true execute the statements
}

In IF construct we have to check the expression, whether is it TRUE or FALSE.

If the expression is TRUE, the statements following it will be executed.

<html>
<head>
<title> My PHP page</title>
</head>
<body>
<?php
$a=20;
$b=50;
If ($b>$a)
{
    echo $b;
}
?>
</body>
</html>

Above code will display

  1.  

2. If......else

The flowchart of this construct is:

3. else if

The flowchart of this construct is:

4. Switch.....case

The flowchart of this construct is:

3. Iterative

These types of constructs can be used when we need to execute a set of statements multiple times. We can use Loops in several ways:

  1. Execute the loop once, and then evaluate the condition, if it is true repeat the loop. (do....while loop)
  2. Firstly evaluate the condition then execute the loop till then condition is true. (While loop)
  3. Repeat the statements for a specified number of times. (for loop)
  4. Repeat the loop for each element of array (foreach loop)

Features of Loops

  1. Break

It is used to break a loop, after verifying the situation if we want to break the loop.

  1. Continue

It is used to continue some set of statements after verifying the situation (condition) in program.

For loop:

This loop is used when we know in advance how many times the loop will execute. The flowchart of this tool is:

 

The syntax of this loop is:

for initialization; expression/condition; increment/decrement)
{
    // code to execute
}
<?php
$sum=0;
for ($i=1;$i<=5;$i++)
{
    $sum=$sum+$i;
}
echo $sum;
?>

​Output of above code is the result of first 5 natural numbers

While loop:

This loop is used to check condition first, and then execute the set of statements till the condition is true.

Flowchart of while loop is:

The syntax of while loop is:

while (condition)
{
    // code to execute
}

<?php
$sum=0;
$i=1;
while($i<=5)
{
    $sum+=$i;
    $i++;
}
echo $sum;
?>

Output of above code is the result of first 5 natural numbers

do...while loop

This loop is also called exit control loop, because in this loop firstly the statements are executed and then the condition is to be checked. The loop will continue till the condition is true. This loop executes at least once, even the condition is false.

Flowchart of do...while loop

The syntax of do...while loop:

do
{
    // code to execute
} while (condition);

<?php
$sum=0;
$i=1;
do{
    $sum+=$i;
    $i++;
}
while($i<=5);
echo $sum;
?>

Output of above code is the result of first 5 natural numbers

foreach loop

This loop is basically used with arrays, when number of elements not known. This loop will execute each value of array.

The syntax of foreach loop is:

foreach(<array_variablename> as <variablename>)
{
    //code to execute
}

Example:

<?php
$myArray=Array(12,13,14,15,16,17);
$sum=0;
foreach($myArray as $i)
{
    $sum+=$i;          
}
echo $sum;
?>

    The output of above code is: sum of elements of array:

    Like us on Facebook