Saturday 18 October 2014

PHP 5 Strings

They are sequences of characters, like "PHP supports string operations".
NOTE: Built-in string functions is given in function reference PHP String Functions
Following are valid examples of string
$string_1 = "This is a string in double quotes";
$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their values as well as specially interpreting certain character sequences.
<?
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
$literally = "My $variable will print!\\n";
print($literally);
?>
This will produce following result:
My $variable will not print!\n
My name will print
There are no artificial limits on string length - within the bounds of available memory, you ought to be able to make arbitrarily long strings.
Strings that are delimited by double quotes (as in "this") are preprocessed in both the following two ways by PHP:
  • Certain character sequences beginning with backslash (\) are replaced with special characters
  • Variable names (starting with $) are replaced with string representations of their values.
The escape-sequence replacements are:
  • \n is replaced by the newline character
  • \r is replaced by the carriage-return character
  • \t is replaced by the tab character
  • \$ is replaced by the dollar sign itself ($)
  • \" is replaced by a single double-quote (")
  • \\ is replaced by a single backslash (\)

String Concatenation Operator

To concatenate two string variables together, use the dot (.) operator:
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>
This will produce following result:
Hello World 1234
If we look at the code above you see that we used the concatenation operator two times. This is because we had to insert a third string.
Between the two string variables we added a string with a single character, an empty space, to separate the two variables.


Using the strlen() function

The strlen() function is used to find the length of a string.
Let's find the length of our string "Hello world!":
<?php
echo strlen("Hello world!");
?>
This will produce following result:
12
The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string)

Using the strpos() function

The strpos() function is used to search for a string or character within a string.
If a match is found in the string, this function will return the position of the first match. If no match is found, it will return FALSE.
Let's see if we can find the string "world" in our string:
<?php
echo strpos("Hello world!","world");
?>
This will produce following result:
6
As you see the position of the string "world" in our string is position 6. The reason that it is 6, and not 7, is that the first position in the string is 0, and not 1.

PHP 5 Arrays

An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.
There are three different kind of arrays and each array value is accessed using an ID c which is called array index.
  • Numeric array - An array with a numeric index. Values are stored and accessed in linear fashion
  • Associative array - An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
  • Multidimensional array - An array containing one or more arrays and values are accessed using multiple indices
NOTE: Built-in array functions is given in function reference PHP Array Functions

Numeric Array

These arrays can store numbers, strings and any object but their index will be prepresented by numbers. By default array index starts from zero.

Example

Following is the example showing how to create and access numeric arrays.
Here we have used array() function to create array. This function is explained in function reference.
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
  echo "Value is $value <br />";
}
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";

foreach( $numbers as $value )
{
  echo "Value is $value <br />";
}
?>
</body>
</html>
This will produce following result:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five

Associative Arrays

The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary.
NOTE: Don't keep associative array inside double quote while printing otheriwse it would not return any value.

Example

<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array( 
     "mohammad" => 2000, 
     "qadir" => 1000, 
     "zara" => 500
    );

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ".  $salaries['qadir']. "<br />";
echo "Salary of zara is ".  $salaries['zara']. "<br />";

/* Second method to create array. */
$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ".  $salaries['qadir']. "<br />";
echo "Salary of zara is ".  $salaries['zara']. "<br />";
?>
</body>
</html>
This will produce following result:
Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low

Multidimensional Arrays

A multi-dimensional array each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.

Example

In this example we create a two dimensional array to store marks of three students in three subjects:
This example is an associative array, you can create numeric array in the same fashion.
<html>
<body>
<?php
   $marks = array( 
  "mohammad" => array
  (
  "physics" => 35,     
  "maths" => 30,     
  "chemistry" => 39     
  ),
  "qadir" => array
                (
                "physics" => 30,
                "maths" => 32,
                "chemistry" => 29
                ),
                "zara" => array
                (
                "physics" => 31,
                "maths" => 22,
                "chemistry" => 39
                )
      );
   /* Accessing multi-dimensional array values */
   echo "Marks for mohammad in physics : " ;
   echo $marks['mohammad']['physics'] . "<br />"; 
   echo "Marks for qadir in maths : ";
   echo $marks['qadir']['maths'] . "<br />"; 
   echo "Marks for zara in chemistry : " ;
   echo $marks['zara']['chemistry'] . "<br />"; 
?>
</body>
</html>
This will produce following result:
Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39

PHP Loop Types

Loops in PHP are used to execute the same block of code a specified number of times. PHP supports following four loop types.
  • for - loops through a block of code a specified number of times.
  • while - loops through a block of code if and as long as a specified condition is true.
  • do...while - loops through a block of code once, and then repeats the loop as long as a special condition is true.
  • foreach - loops through a block of code for each element in an array.
We will discuss about continue and break keywords used to control the loops execution.

The for loop statement

The for statement is used when you know how many times you want to execute a statement or a block of statements.

Syntax

for (initialization; condition; increment)
{
  code to be executed;
}
The initializer is used to set the start value for the counter of the number of loop iterations. A variable may be declared here for this purpose and it is traditional to name it $i.

Example

The following example makes five iterations and changes the assigned value of two variables on each pass of the loop:
<html>
<body>
<?php
$a = 0;
$b = 0;

for( $i=0; $i<5; $i++ )
{
    $a += 10;
    $b += 5;
}
echo ("At the end of the loop a=$a and b=$b" );
?>
</body>
</html>
This will produce following result:
At the end of the loop a=50 and b=25

The while loop statement

The while statement will execute a block of code if and as long as a test expression is true.
If the test expression is true then the code block will be executed. After the code has executed the test expression will again be evaluated and the loop will continue until the test expression is found to be false.

Syntax

while (condition)
{
    code to be executed;
}

Example

This example decrements a variable value on each iteration of the loop and the counter increments until it reaches 10 when the evaluation is false and the loop ends.
<html>
<body>
<?php
$i = 0;
$num = 50;

while( $i < 10)
{
   $num--;
   $i++;
}
echo ("Loop stopped at i = $i and num = $num" );
?>
</body>
</html>
This will produce following result:
Loop stopped at i = 10 and num = 40 

The do...while loop statement

The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true.

Syntax

do
{
   code to be executed;
}while (condition);

Example

The following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 10:
<html>
<body>
<?php
$i = 0;
$num = 0;
do
{
  $i++;
}while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
This will produce following result:
Loop stopped at i = 10

The foreach loop statement

The foreach statement is used to loop through arrays. For each pass the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.

Syntax

foreach (array as value)
{
    code to be executed;

}

Example

Try out following example to list out the values of an array.
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
  echo "Value is $value <br />";
}
?>
</body>
</html>
This will produce following result:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5

The break statement

The PHP break keyword is used to terminate the execution of a loop prematurely.
The break statement is situated inside the statement block. If gives you full control and whenever you want to exit from the loop you can come out. After coming out of a loop immediate statement to the loop will be executed.

Example

In the following example condition test becomes true when the counter value reaches 3 and loop terminates.
<html>
<body>

<?php
$i = 0;

while( $i < 10)
{
   $i++;
   if( $i == 3 )break;
}
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
This will produce following result:
Loop stopped at i = 3

The continue statement

The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate the loop.
Just like the break statement the continue statement is situated inside the statement block containing the code that the loop executes, preceded by a conditional test. For the pass encountering continue statement, rest of the loop code is skipped and next pass starts.

Example

In the following example loop prints the value of array but for which condition becomes true it just skip the code and next value is printed.
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
  if( $value == 3 )continue;
  echo "Value is $value <br />";
}
?>
</body>
</html>
This will produce following result
Value is 1
Value is 2
Value is 4
Value is 5

Friday 17 October 2014

PHP 5 if..else..elseif Statements

Conditional statements are used to perform different actions based on different conditions.

PHP Conditional Statements

Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
  • if statement - executes some code only if a specified condition is true
  • if...else statement - executes some code if a condition is true and another code if the condition is false
  • if...elseif....else statement - selects one of several blocks of code to be executed
  • switch statement - selects one of many blocks of code to be executed

PHP - The if Statement

The if statement is used to execute some code only if a specified condition is true.

Syntax

if (condition) {
  code to be executed if condition is true
;
}
The example below will output "Have a good day!" if the current time (HOUR) is less than 20:

Example

<?php
$t=date("H");

if ($t<"20") {
  echo "Have a good day!";
}
?>


PHP - The if...else Statement

Use the if....else statement to execute some code if a condition is true and another code if the condition is false.

Syntax

if (condition) {
  code to be executed if condition is true;
} else {
  code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less than 20, and "Have a good night!" otherwise:

Example

<?php
$t=date("H");

if ($t<"20") {
  echo "Have a good day!";
} else {
  echo "Have a good night!";
}
?>


PHP - The if...elseif....else Statement

Use the if....elseif...else statement to select one of several blocks of code to be executed.

Syntax

if (condition) {
  code to be executed if condition is true;
} elseif (condition) {
  code to be executed if condition is true;
} else {
  code to be executed if condition is false;
}
The example below will output "Have a good morning!" if the current time is less than 10, and "Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good night!":

Example

<?php
$t=date("H");

if ($t<"10") {
  echo "Have a good morning!";
} elseif ($t<"20") {
  echo "Have a good day!";
} else {
  echo "Have a good night!";
}
?>

PHP 5 Operators

This chapter shows the different operators that can be used in PHP scripts.

PHP Arithmetic Operators

Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y Result of raising $x to the $y'th power (Introduced in PHP 5.6)
The example below shows the different results of using the different arithmetic operators:

Example

<?php
$x=10;
$y=6;
echo ($x + $y); // outputs 16
echo ($x - $y); // outputs 4
echo ($x * $y); // outputs 60
echo ($x / $y); // outputs 1.6666666666667
echo ($x % $y); // outputs 4
?>


PHP Assignment Operators

The PHP assignment operators are used to write a value to a variable.
The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right.
Assignment Same as... Description
x = y x = y The left operand gets set to the value of the expression on the right
x += y x = x + y Addition
x -= y x = x - y Subtraction
x *= y x = x * y Multiplication
x /= y x = x / y Division
x %= y x = x % y Modulus
The example below shows the different results of using the different assignment operators:

Example

<?php
$x=10;
echo $x; // outputs 10

$y=20;
$y += 100;
echo $y; // outputs 120

$z=50;
$z -= 25;
echo $z; // outputs 25

$i=5;
$i *= 6;
echo $i; // outputs 30

$j=10;
$j /= 5;
echo $j; // outputs 2

$k=15;
$k %= 4;
echo $k; // outputs 3
?>


PHP String Operators

Operator Name Example Result
. Concatenation $txt1 = "Hello"
$txt2 = $txt1 . " world!"
Now $txt2 contains "Hello world!"
.= Concatenation assignment $txt1 = "Hello"
$txt1 .= " world!"
Now $txt1 contains "Hello world!"
The example below shows the results of using the string operators:

Example

<?php
$a = "Hello";
$b = $a . " world!";
echo $b; // outputs Hello world!

$x="Hello";
$x .= " world!";
echo $x; // outputs Hello world!
?>



PHP Increment / Decrement Operators

Operator Name Description
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
The example below shows the different results of using the different increment/decrement operators:

Example

<?php
$x=10;
echo ++$x; // outputs 11

$y=10;
echo $y++; // outputs 10

$z=5;
echo --$z; // outputs 4

$i=5;
echo $i--; // outputs 5
?>


PHP Comparison Operators

The PHP comparison operators are used to compare two values (number or string):
Operator Name Example Result
== Equal $x == $y True if $x is equal to $y
=== Identical $x === $y True if $x is equal to $y, and they are of the same type
!= Not equal $x != $y True if $x is not equal to $y
<> Not equal $x <> $y True if $x is not equal to $y
!== Not identical $x !== $y True if $x is not equal to $y, or they are not of the same type
> Greater than $x > $y True if $x is greater than $y
< Less than $x < $y True if $x is less than $y
>= Greater than or equal to $x >= $y True if $x is greater than or equal to $y
<= Less than or equal to $x <= $y True if $x is less than or equal to $y
The example below shows the different results of using some of the comparison operators:

Example

<?php
$x=100;
$y="100";

var_dump($x == $y);
echo "<br>";
var_dump($x === $y);
echo "<br>";
var_dump($x != $y);
echo "<br>";
var_dump($x !== $y);
echo "<br>";

$a=50;
$b=90;

var_dump($a > $b);
echo "<br>";
var_dump($a < $b);
?>


PHP Logical Operators

Operator Name Example Result
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true


PHP Array Operators

The PHP array operators are used to compare arrays:
Operator Name Example Result
+ Union $x + $y Union of $x and $y (but duplicate keys are not overwritten)
== Equality $x == $y True if $x and $y have the same key/value pairs
=== Identity $x === $y True if $x and $y have the same key/value pairs in the same order and of the same types
!= Inequality $x != $y True if $x is not equal to $y
<> Inequality $x <> $y True if $x is not equal to $y
!== Non-identity $x !== $y True if $x is not identical to $y
The example below shows the different results of using the different array operators:

Example

<?php
$x = array("a" => "red", "b" => "green");
$y = array("c" => "blue", "d" => "yellow");
$z = $x + $y; // union of $x and $y
var_dump($z);
var_dump($x == $y);
var_dump($x === $y);
var_dump($x != $y);
var_dump($x <> $y);
var_dump($x !== $y);
?>

PHP 5 Constants

Constants are like variables except that once they are defined they cannot be changed or undefined.

PHP Constants

A constant is an identifier (name) for a simple value. The value cannot be changed during the script.
A valid constant name starts with a letter or underscore (no $ sign before the constant name).
Note: Unlike variables, constants are automatically global across the entire script.

Set a PHP Constant

To set a constant, use the define() function - it takes three parameters: The first parameter defines the name of the constant, the second parameter defines the value of the constant, and the optional third parameter specifies whether the constant name should be case-insensitive. Default is false.
The example below creates a case-sensitive constant, with the value of "Welcome to Ajay Online Zone":

Example

<?php
define("GREETING", "Welcome to Ajay Online Zone");
echo GREETING;
?>

The example below creates a case-insensitive constant, with the value of "Welcome to Ajay Online Zone":

Example

<?php
define("GREETING", "Welcome to Ajay Online Zone", true);
echo greeting;
?>

PHP 5 String Functions

A string is a sequence of characters, like "Hello world!".

PHP String Functions

In this chapter we will look at some commonly used functions to manipulate strings.

The PHP strlen() function

The strlen() function returns the length of a string, in characters.
The example below returns the length of the string "Hello world!":

Example

<?php
echo strlen("Hello world!");
?>

The output of the code above will be: 12
Tip: strlen() is often used in loops or other functions, when it is important to know when a string ends. (i.e. in a loop, we might want to stop the loop after the last character in a string).

The PHP strpos() function

The strpos() function is used to search for a specified character or text within a string.
If a match is found, it will return the character position of the first match. If no match is found, it will return FALSE.
The example below searches for the text "world" in the string "Hello world!":

Example

<?php
echo strpos("Hello world!","world");
?>

The output of the code above will be: 6.
Tip: The position of the string "world" in the example above is 6. The reason that it is 6 (and not 7), is that the first character position in the string is 0, and not 1.