PHP BASIC PART-3 ( PHP Conditional Statement, Arrays and Array Functions )

Making Decisions with the PHP if  and else Statement

The PHP if statement lets a script test to see if a certain condition is true, and run a chunk of code if it is. This allows your code to make decisions about what to do next, thereby adding a lot of power to your scripts.

PHP if syntax

A PHP if construct takes the following general format:

if ( condition ) {
  // This code is run if condition is true
}
 
// This code is run anyway

Here’s how it works:

  1. The PHP engine tests the condition inside the parentheses.
  2. If the condition is true then the PHP engine runs the code inside the braces ({}), then it starts running any code after the closing brace.
  3. If the condition is false then the PHP engine skips the code inside the braces, and starts running any code after the closing brace.

Some examples using the if statement

Here’s a simple example script showing the PHP if statement in action:


<?php
$numWidgets = 3;

if ( $numWidgets > 1 ) {
echo "We have more than 1 widget in stock!<br />";
}

echo "Number of widgets: $numWidgets<br />";
?>

When run, this code displays the following in a Web browser:

We have more than 1 widget in stock!
Number of widgets: 3

The script sets a $numWidgetsvariable to 3, then tests the variable to see if its value is greater than 1. Since it is, the code inside the braces is run and the message

“We have more than 1 widget in stock!”is displayed. Finally the code after the if block is run, displaying

“Number of widgets: 3″.

What happens if $numWidgets isn’t greater than 1?


<?php

$numWidgets = 0;

if ( $numWidgets > 1 ) {
echo "We have more than 1 widget in stock!<br />";
}

echo "Number of widgets: $numWidgets<br />";

?>

This code displays:

Number of widgets: 0

Since $numWidgets isn’t greater than 1, the code inside the if block is skipped and the first message isn’t displayed.

Choosing between chunks of code with if ... else

You can enhance the if statement with the else statement. This lets you run one chunk of code if a condition is true, or a different chunk of code if the condition is false:

if ( condition ) {
  // This code is run if condition is true
} else {
  // This code is run if condition is false
}
 
// This code is run anyway

Here’s an example that uses if ... else:


<?php
$numWidgets = 0;

if ( $numWidgets >= 1 ) {
echo "We have at least 1 widget in stock<br />";
} else {
echo "We have less than 1 widget in stock<br />";
}

echo "Number of widgets: $numWidgets<br />";
?>

This code displays:

We have less than 1 widget in stock
Number of widgets: 0

$numWidgets is less than 1, so the condition $numWidgets >= 1 is false. Therefore the PHP engine runs the code inside the else block, displaying the message "We have less than 1 widget in stock".

Making Decisions with the PHP elseif Statement

The PHP if and else statements let a script decide whether to run a chunk of code based on a condition. The if statement runs a chunk of code if the condition is true or skips it if the condition is false. if combined with else runs one chunk if the condition is true, or the other chunk if the condition is false.

PHP lets you take things further, and chain several decision-making blocks together, with each block having its own condition to test. To do this, you use the elseif statement.

Syntax of the PHP elseif statement

The simplest form of an if ... elseif block has the following structure:

if ( condition1 ) {
  // This code is run if condition1 is true
} elseif ( condition2 ) {
  // This code is run if condition1 is false and condition2 is true
}
 
// This code is run anyway
 

Here’s how it works:

  • Firstly, condition1 is tested. If it’s true then the first block of code — between the if and elseif statements — is run. The PHP engine then skips to the first line of code after the whole if ... elseif block (the last line of code in the above example).
  • If condition1 is false then condition2 is tested. If this condition is true then the second block of code — between the elseif statement and the final closing brace — is run. Once again, the PHP engine then skips to the first line of code after the if ... elseif block.
  • If condition2 is also false then neither blocks of code inside the if ... elseif block are run. Execution continues with the first line of code after the if ... elseif block.

You can have as many elseif blocks as you like. Each condition in turn is tested; if it’s true then the code in the block is run, otherwise the PHP engine moves onto the next elseif block:

 
if ( condition1 ) {
  // This code is run if condition1 is true
} elseif ( condition2 ) {
  // This code is run if condition1 is false and condition2 is true
} elseif ( condition3 ) {
  // This code is run if condition1 and condition2 are false and condition3 is true
}
 
// This code is run anyway

You can also add an else block after your elseif block(s). The else block is run if all the previous if and elseif conditions are false:

if ( condition1 ) {
  // This code is run if condition1 is true
} elseif ( condition2 ) {
  // This code is run if condition1 is false and condition2 is true
} else {
  // This code is run if neither condition1 or condition2 are true
}
 
// This code is run anyway

If you prefer, you can write elseif as two words: else if.

A PHP elseif example

Here’s an example that uses if, elseif and else:


<?php

$numWidgets = 2;

if ( $numWidgets > 2 ) {
echo "We have more than 2 widgets in stock<br />";
} elseif ( $numWidgets < 2 ) {
echo "We have less than 2 widgets in stock<br />";
} else {
echo "We have exactly 2 widgets in stock<br />";
}

echo "Number of widgets: $numWidgets<br />";

?>

This code displays:

We have exactly 2 widgets in stock
Number of widgets: 2

While Loops

PHP loops let you run a block of PHP code over and over again. They’re great for repetitive tasks such as reading data records from a database, or displaying rows of a table in a Web page.

The PHP while loop is the simplest type of loop to understand. In this article you look at the syntax of a PHP while loop, and explore some example loops. You also look at do...while loops.

What is a while loop?

A while loop is a construct that lets you run a block of code repeatedly as long as a certain condition is true. As soon as the condition becomes false, the loop exits.

Here’s the general syntax of a PHP while loop:

while ( condition ) {
  // This code is run as long as condition is true
}
 
// This code is run after the loop finishes

Here’s how it works:

  1. The PHP engine tests the condition inside the parentheses.
  2. If the condition is true then the PHP engine runs the code inside the braces ({}), then retests the condition. If it’s still true then the code inside the braces is run again, and so on.
  3. If the condition is false then the PHP engine exits the loop, and starts running any code after the closing brace.

Typically, you write the condition in such a way that it is true while you want your loop to run, and becomes false when you want your loop to exit. For example, if your loop should count to ten before exiting then the condition might be:

while ( $counter <= 10 ) {
...

A PHP while loop example

Here’s a simple example script that uses a while loop to count from 1 to 10:


<?php

$counter = 1;

while ( $counter <= 10 ) {
echo "I've counted to $counter<br />";
$counter++;
}

echo "All done!";

?>

When run, this code displays the following in a Web browser:

I've counted to 1
I've counted to 2
I've counted to 3
I've counted to 4
I've counted to 5
I've counted to 6
I've counted to 7
I've counted to 8
I've counted to 9
I've counted to 10
All done!

The script first sets a $counter variable to 1. Then it starts looping. Each time through the loop, $counter is tested to make sure it’s still less than or equal to 10; as long as it is, the loop repeats. Inside the loop, the current value of $counter is displayed, then $counter is incremented by 1.

Once $counter reaches 11, the condition in the while loop becomes false and the loop exits, displaying the “All done!” message.

The PHP do...while loop

The do...while loop is a variation of the while loop. The only difference is that the expression is tested after the code block has been run, rather than before:

do {
  // This code is run at least once
} while ( condition )
 
// This code is run after the loop finishes

Here’s how a do...while loop runs:

  1. The PHP engine first runs the code block inside the braces ({}).
  2. Next, the PHP engine tests the condition inside the parentheses.
  3. If the condition is true then the code inside the braces is run again, and so on.
  4. If the condition is false then the PHP engine exits the loop, and starts running any code after the closing brace.

You can see that, with a do...while loop, the code inside the loop is always run at least once, even if the condition is false to start with. This can be useful in certain situations. For example, if your condition includes a variable that is set inside the loop then you need to run the loop at least once before you can test the condition.

Here’s an example of a do...while loop — a simple number-guessing game:


<?php

$theNumber = rand ( 1, 10 );

do {
$myGuess = rand ( 1, 10 );
echo "I'm guessing: $myGuess</br />";
} while ( $myGuess != $theNumber );

echo "I got it! It's $myGuess!<br />";

?>

The script displays something like this:

I'm guessing: 3
I'm guessing: 5
I'm guessing: 7
I'm guessing: 2
I got it! It's 2!

First, the script sets a new variable, $theNumber, to a random number between 1 and 10. Then it begins the do...while loop. Within the loop, the script sets another variable, $myGuess, to another random number between 1 and 10, and displays the guess.

Next, the loop condition tests to see if $theNumber and $myGuess are different; if they are then the loop runs again so that another guess can be made. This repeats until $myGuess equals $theNumber; at this point the loop exits and the script displays a success message.

Note: The built-in PHP function rand() takes two numbers and returns a whole random number between those two numbers (inclusive).

For Loops

PHP loops allow you to run the same chunk of code repeatedly. PHP features while and do…while loops, which are handy for general-purpose looping, and the more specialized for loop, which is useful when you want to run a chunk of code a known number of times.

This article explains how PHP for loops work, and shows you some practical for loop examples.

PHP for loop syntax

PHP for loops have the following general syntax:

for ( expression1; expression2; expression3 ) {
  // This code is run as long as expression2 is true
}
 
// This code is run after the loop finishes

You can see that for loops are more complex than while loops — whereas a while loop has 1 expression between the parentheses, a for loop has 3 expressions, separated by semicolons.

Here’s how a for loop works:

  1. The first time through the loop, the PHP engine evaluates expression1. This expression is known as the initialize, and is usually used to set up a counter variable for the loop.
  2. At the start of each iteration of the loop, expression2 is tested. If it’s true, the loop continues and the code inside the braces ({}) is run. If it’s false the loop exits, and any code after the closing brace is run. expression2 is known as the loop test, and serves the same purpose as the single expression in a while loop.
  3. After each iteration, the PHP engine evaluates expression3. This expression is known as the counting expression, and is usually used to change the counter variable.

Some for loop examples

for loops are primarily designed to run a chunk of code a known number of times. Here’s a simple example:


<?php

for ( $i = 1; $i <= 5; $i++ ) {
echo "Counted to $i...<br />";
}

echo "Finished!";

?>

When run, this code displays the following:

Counted to 1...
Counted to 2...
Counted to 3...
Counted to 4...
Counted to 5...
Finished!

You can see how the 3 expressions in a for loop make it easy to set up and increment a counter variable, $i, for looping a known number of times.

You don’t have to count upwards though, as the following examples show:


<?php

// Count backwards from 5 to 1

for ( $i = 5; $i >= 1; $i-- ) {
echo "$i...<br />";
}

echo "Finished!<br /><br />";

// Display all powers of 2 less than 40

for ( $num = 1; $num < 40; $num *= 2 ) {
echo "$num...<br />";
}

echo "Finished!<br />";

?>

The above code displays the following:

5...
4...
3...
2...
1...
Finished!

1...
2...
4...
8...
16...
32...
Finished!

A real-world example: generating passwords

Say you want to generate an 8-character random password for a user. A for loop is perfect here, since you know in advance how many times you want the loop to run (8 in this case):


<?php

$password = "";

for ( $i = 0; $i < 8; $i++ ) {
$password .= chr ( rand ( 0, 25 ) + 97 );
}

echo "Your new password is: $password";

?>

This displays something like:

Your new password is: fynqtfxs

for loop expressions are optional

It’s worth pointing out that each of the 3 expressions in a for loop is optional. (If you miss out the loop test expression then it defaults to true, making the loop continue forever.)

An example:


<?php

$num1 = 1;
$num2 = 5;

for ( ; $num1 <= $num2; $num1++ ) {
echo "$num1...<br />";
}

echo "Finished!<br /><br />";

?>

This code displays:

1...
2...
3...
4...
5...
Finished!

For statement without all three statements

<?php
// Example Three
$kilometers = 1;
for (;;) {
if ($kilometers > 5) break;
echo "$kilometers kilometers = ".$kilometers*0.62140. " miles. <br />";
$kilometers++;
}
?>

For statement without second condition

<?php
// Example Two
for ($kilometers = 1; ; $kilometers++) {
if ($kilometers > 5) break;
echo "$kilometers kilometers = ".$kilometers*0.62140. " miles. <br />";
}
?>

Nesting Two for Loops


<?php

<html>
<head><title>Nesting Two for Loops</title></head>
<body>
<div>
<?php
print "<table>";
for ( $y=1; $y<=12; $y++ ) {
print "<tr>";
for ( $x=1; $x<=12; $x++ ) {
print "<td>";
print ($x*$y);
print "</td>";
}
print "</tr>";
}
print "</table>";
?>
</div>
</body>
</html>

?>

Continue……

 

Example:

 

Continue within while loop

 

Result: 1 2 3 4 5 6 7 8 9 10


<html>
<head>
<title>A Simple Page</title>
</head>
<body>
<?php

$x = 0;
while ($x < 10)
{
$x++;
echo "  ".$x;
continue;
print("You never see this!");
}
?>

</body>
</html>

Example:

 

continue within a for loop

 

Reslult:

 

Staff member: grace
Staff member: doris
Staff member: gary
Staff member: nate
Staff member: tom


<?php
$usernames = array("grace","doris","gary","nate","missing","tom");
for ($x=0; $x < count($usernames); $x++) {
if ($usernames[$x] == "missing") continue;
echo "Staff member: $usernames[$x] <br />";
}
?>

Example:

 

Result:

 

100/-3 -33.333333333333
100/-2 -50
100/-1 -100
Skipping to avoid division by zero.
100/1 100
100/2 50
100/3 33.333333333333
100/4 25
100/5 20
100/6 16.666666666667
100/7 14.285714285714
100/8 12.5
100/9 11.111111111111

 

Using continue instead of break


<?php

$counter=-3;

for (;$counter<10;$counter++){
if ($counter==0){
echo “Skipping to avoid division by zero.<br>”;
continue;
}

echo “100/$counter “,100/$counter,”<br />”;
}

?>

Break Statement

 

Example:

Break Statement


<html>
<head>
<title>Break Statement</title>
</head>
<body>

<?php
$i = 0;

while ( $i < 6 )
{
if( $i == 3) break;
$i++;
}
echo("Loop stopped at $i by break statement");
?>

</body>
</html>

Example:

Result:

4000 divided by -4 is.. -1000
4000 divided by -3 is.. -1333.3333333333
4000 divided by -2 is.. -2000
4000 divided by -1 is.. -4000

 

Using the break Statement


<html>
<head><title>Using the break Statement</title></head>
<body>
<div>
<?php
$counter = -4;
for ( ; $counter <= 10; $counter++ ) {
if ( $counter == 0 ) {
break;
}
$temp = 4000/$counter;
print "4000 divided by $counter is.. $temp<br />";
}
?>
</div>
</body>
</html>

Example:

 

Result:

 

Non-prime number encountered: 1

Non-prime number encountered: 49

Non-prime number encountered: 33

 

break within a for loop


<?php
$primes = array(2,3,5,7,11,13);
for($count = 1; $count++; $count < 1000) {
$randomNumber = rand(1,50);
if (in_array($randomNumber,$primes)) {
break;
} else {
echo "<p>Non-prime number encountered: $randomNumber</p>";
}
}
?>

Example:

 

Using break to avoid division by zero


<?php

$counter = -3;

for (; $counter < 10; $counter++){
if ($counter == 0){
echo "Stopping to avoid division by zero.";
break;
}

echo "100/$counter<br />";
}

?>

Switch

 

Use the ‘default’ case


<?php
$nIndex = 17;
switch ( $nIndex )
{
case 0:
print( "zero<br>" );
break;
case 1:
print( "one<br>" );
break;
case 2:
print( "two<br>" );
break;
default:
print( "neither zero, one nor two<br>" );
break;
}
?>

Using switch to test for multiple values


<?php
$action = "ADD";
switch ($action) {
case "ADD":
echo "Perform actions for adding.";
break;
case "MODIFY":
echo "Perform actions for modifying.";
break;
case "DELETE":
echo "Perform actions for deleting.";
break;
}
?>

PHP Array

Now we explain how arrays work in PHP, and show how to create and manipulate arrays.

Creating Arrays in PHP

Now we Explains how arrays work in PHP, and shows how to create both indexed and associative arrays.

Like most programming languages, PHP lets you create arrays. An array is a special type of variable that can hold many values at once, all accessible via a single variable name. Arrays are very useful whenever you need to work with large amounts of data — such as records from a database — or group related data together.

In this article, you’ll:

  •     Learn how PHP arrays work, and why they’re useful
  •     Look at the difference between indexed arrays and associative arrays, and
  •     Learn how to create arrays within your PHP scripts.

How arrays work

As you’ve seen already, arrays are variables that can hold more than one value. Here are some more key facts about arrays in PHP:

  •     An array can hold any number of values, including no values at all.
  •     Each value in an array is called an element.
  •     You access each element via its index, which is a numeric or string value. Every element in an array has its own unique index.
  •     An element can store any type of value, such as an integer, a string, or a Boolean. You can mix types within an array — for example, the first element can contain an integer, the second can contain a string, and so on.
  •     An array’s length is the number of elements in the array.
  •     An array element’s value can itself be an array. This allows you to create multidimensional arrays.

Why arrays are useful

Arrays in PHP offer many benefits, including the following:

  • They’re easy to manipulate. It’s easy to add or remove elements in an array, as well as read or change the value of an element.
  • It’s easy to work with many values at once. You can easily loop through all elements in an array, reading or changing each element’s value as you move through the loop.
  • PHP gives you many handy array-related functions. For example, you can sort array elements quickly and easily; search arrays for particular values or indices; and merge arrays together.

Indexed arrays and associative arrays

PHP lets you create 2 types of array:

  • Indexed arrays have numeric indices. Typically the indices in an indexed array start from zero, so the first element has an index of 0, the second has an index of 1, and so on. Usually, you use an indexed array when you want to store a bunch of data in a certain order.
  • Associative arrays have string indices. For example, one element of an associative array might have an index of "name", while another element has an index of "age". The order of the elements is usually unimportant. Typically, you use an associative array when you want to store records of data, much like using a database.

In fact, PHP doesn’t make any internal distinction between indexed and associative arrays. You can even mix numeric and string indices within the same array if you like. Most of the time, however, it helps to think of indexed and associative arrays as different types of arrays. Furthermore, many PHP array functions are designed to work with either indexed or associative arrays.

How to create an array in PHP

It’s easy to create an array within a PHP script. To create an array, you use the array() construct:


$myArray = array( values );

To create an indexed array, just list the array values inside the parentheses, separated by commas. The following example creates an indexed array of movie director names and stores it in a variable called $directors:

<?php
$directors = array( "Sharif", "Rahim, "Dulal", "Hafiz" );
?>

When creating an indexed array, PHP automatically assigns a numeric index to each element. In the above example, "Sharif" is given an index of 0, "Rahim" has an index of 1, and so on.

To create an associative array, you pair each value with the index that you want to use for that value. To do this you use the => operator:

index => value

The following example creates an associative array with information about a movie, and stores it in a variable called $movie:

$movie = array( "title" => "Rear Window",
"director" => "Alfred Hitchcock",
"year" => 1954 );

By the way, to create an array with no elements, you can write:

$myArray = array();

Working With Array Elements in PHP

In Creating Arrays in PHP, you learned how PHP arrays work, and saw how to create an array using PHP.

Now take things further, and look at how to access the individual elements inside a PHP array. You’ll see how to:

  • Read element values
  • Alter element values
  • Add and remove elements in an array
  • Output the entire contents of an array

Changing element values

You assign a new value to an array element in the same way as a regular variable:

$myArray[index] = new value;

The following example changes the 3rd element of the array from “Martin Scorsese” to “Woody Allen”:


<?php

$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );
$directors[2] = "Woody Allen";
?>

Adding elements

You can add a new element to an array like this:

$myArray[] = value;

PHP automatically assigns the next available numeric index to the new element. Here’s an example:


<?php

$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );
$directors[] = "Woody Allen";

// Displays "Woody Allen"
echo $directors[4];

?>

You can also specify an index. If an element with that index already exists in the array, its value is overwritten; otherwise a new element is created with that index:


<?php

$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );
$directors[4] = "Woody Allen";

// Displays "Woody Allen"
echo $directors[4];

$directors[2] = "Ingmar Bergman";

// Displays "Ingmar Bergman"
echo $directors[2];

?>

Removing elements

To remove an element from an array, you call unset(), passing in the element to remove. (You can also use unset() on regular variables to delete them.) Here’s an example:


<?php

$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );

// Displays "Stanley Kubrick"
echo $directors[1];

unset( $directors[1] );

// Displays nothing (and generates an "Undefined offset" notice)
echo $directors[1];

?>

note: The last line of code above generates an “Undefined offset” notice, which is a minor error. It means that you’re trying to access an array index that doesn’t exist. Normally, PHP doesn’t display or log notices, but you can change this with the error_reporting() function.

unset() doesn’t automatically reindex arrays to “close the gap” in the index numbering. For example, after running the above code, "Martin Scorsese" still has an index of 2, and "Fritz Lang" still has an index of 3. To reindex the array so that the indices are contiguous again, you can use the array_values() function. For example:


<?php
$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );

// Displays "Stanley Kubrick"
echo $directors[1] . "<br />";

unset( $directors[1] );
$directors = array_values( $directors );

// Displays "Martin Scorsese"
echo $directors[1] . "<br />";

?>

Outputting an array with print_r()

Sometimes when debugging your code it’s useful to inspect the entire contents of an array. However, using print() or echo() on an array isn’t much help:


<?php

$directors = array( "Kawser", "Zaman", "Sohel", "Linkon" );

// Displays "Array"
echo $directors;
<pre>?>

To display an entire array, use the print_r() function instead. Here’s an example that creates an indexed array and an associative array, then displays the contents of both arrays using print_r():

<?php
$directors = array( "Sania", "Nigat", "Parvin", "GM" );

$movie = array( "title" => "Rear Window",
"director" => "Alfred Hitchcock",
"year" => 1954 );

echo '<h2>$directors:</h2><pre>';
print_r( $directors );
echo '</pre><h2>$movie:</h2><pre>';
print_r( $movie );
echo "</pre>";
?>

The above code produces the following output:

$directors:

Array
(
[0] => Alfred Hitchcock
[1] => Stanley Kubrick
[2] => Martin Scorsese
[3] => Fritz Lang
)

$movie:

Array
(
[title] => Rear Window
[director] => Alfred Hitchcock
[year] => 1954
)

Counting PHP Array Elements Using count()

Now Explains how to use PHP’s count() function to count the elements in an array, and how to loop through an array with count() and a for loop.

Often it’s useful to know how many elements an array contains. Here are some common reasons for counting the number of elements in an array:

  • You can then use a for loop to move through the elements
  • You can display the total number of elements to the user (such as the number of search results returned)
  • You can calculate the average of the values in the array (in conjunction with array_sum())

PHP makes it easy to count array elements, thanks to its built-in count() function. In this tutorial you’ll learn how to use count() to count the elements in both regular and multidimensional arrays, and how to move through all the elements of an indexed array by using count() and a for loop.

Basic count() usage

Using count() is easy. Just pass it the array whose elements you want to count, and the function returns the number of elements in the array:


<?php

$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );

// Displays "4"
echo count( $directors );

?>

The above example counts the elements in an indexed array, but you can just as easily count an associative array:


<?php

$movie = array( "title" => "Rear Window",
"director" => "Alfred Hitchcock",
"year" => 1954,
"minutes" => 112 );

// Displays "4"
echo count( $movie );

?>

Moving through arrays with count() and for loops

You can use count(), along with your knowledge of for loops and working with array elements, to loop through all the elements in an indexed array:


<?php

$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );

// Displays "Alfred Hitchcock, Stanley Kubrick, Martin Scorsese, Fritz Lang":

$totalElements = count( $directors );

for ( $i=0; $i < $totalElements; $i++ ) {
echo $directors[$i];
if ( $i < $totalElements -1 ) echo ", ";
}

?>

The above code first reads the total number of array elements using count(), and stores the result (4) in $totalElements. It then loops through each element index, from 0 through to $totalElements - 1 (i.e. 3), displaying the element’s value as it goes. (The if statement displays a comma and space after each element except for the last.)

You do need to be bit careful when using count() with for. As you saw in Above, PHP doesn’t distinguish between indexed and associative arrays, and numeric array indices don’t have to be contiguous either. Consider the following example:


<?php

error_reporting(0);
ini_set( 'display_errors', true );

$directors = array( 0 => "Alfred Hitchcock", 1 => "Stanley Kubrick", 2 => "Martin Scorsese", 39 => "Fritz Lang" );

// Displays "Alfred Hitchcock, Stanley Kubrick, Martin Scorsese,"
// and generates an "Undefined offset: 3" notice:

$totalElements = count( $directors );

for ( $i=0; $i < $totalElements; $i++ ) {
echo $directors[$i];
if ( $i < $totalElements -1 ) echo ", ";
}

?>

What’s happening here? The above example is identical to the one before, except that the array indices are no longer contiguous (0, 1, 2, and 39). We’ve also set PHP to display all errors in the browser. When the code tries to read the element with the index of 3, PHP generates an “Undefined offset” notice because an element with this index doesn’t exist.

The lesson here is that count() - 1 only equals the index of the last element in the array when the array indices are contiguously numbered (for example, 0, 1, 2 and 3). Fortunately, this is usually the case with indexed arrays.

If you’re not sure whether the indices of an array are contiguous, you can use other PHP constructs such as foreach to loop through the array’s elements. (More on foreach in a later tutorial.)

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

Counting multidimensional arrays

We touched briefly on multidimensional arrays in Creating Arrays in PHP Section. Essentially, a multidimensional array is an array whose elements are also arrays.

By default, count() only counts the elements in the top level of a multidimensional array. Here’s an example:


<?php

$movieInfo = array( "directors" => array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" ),
"movies" => array( "Rear Window", "2001", "Taxi Driver", "Metropolis" ) );

// Displays "2"
echo count( $movieInfo );

?>

The above code only counts the 2 elements in the top-level array ("directors" and "movies").

If you want to count all the elements in a multidimensional array — that is, not just the top-level elements, but the elements in all arrays inside the array — then pass the constant COUNT_RECURSIVE as a second argument to count():


<?php

$movieInfo = array( "directors" => array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" ),
"movies" => array( "Rear Window", "2001", "Taxi Driver", "Metropolis" ) );

// Displays "10"
echo count( $movieInfo, COUNT_RECURSIVE );

?>

In the above example, count() first counts the 2 elements in the top-level array ("directors" and "movies"). Then it counts all 8 elements in the nested arrays ("Alfred Hitchcock" to "Fritz Lang", then "Rear Window" to "Metropolis"). This results in a grand total of 10 elements.

Using foreach to Loop Through PHP Arrays

How to use PHP’s foreach construct to loop through PHP array elements.

Often you need to move through all the elements in a PHP array so that you can do something with each element’s value. For example, you may want to display each value in an HTML table, or give each element a new value.

In Counting PHP Array Elements Using count(), I showed how you can use a for loop along with the count() function to loop through an array. However, there’s a much easier way to loop through arrays: the foreach construct.

In this article you learn the basic syntax of foreach, and see how to use it to loop through both indexed and associative arrays.

Looping through element values

The simplest way to use foreach is when looping through the values in an indexed array. Here’s the basic syntax:

foreach ( $array as $value ) {
  // Do stuff with $value
}
 
// This code runs after the loop finishes

For example, the following script loops through a list of movie directors in an indexed array, displaying each director’s name as it goes:


<?php

$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );

foreach ( $directors as $director ) {
echo $director . "<br />";
}
?>

The above script produces the following output:

Alfred Hitchcock
Stanley Kubrick
Martin Scorsese
Fritz Lang

Looping through keys and values

So far so good, but what about associative arrays? With these types of arrays, you often want to access each element’s key as well as its value. Luckily, foreach gives you a way to do just that:

foreach ( $array as $key => $value ) {
  // Do stuff with $key and/or $value
}
 
// This code runs after the loop finishes

Here’s an example that loops through an associative array of movie information, displaying each element’s key and value inside an HTML definition list:


<?php

$movie = array( "title" => "Rear Window",
"director" => "Alfred Hitchcock",
"year" => 1954,
"minutes" => 112 );

echo "<dl>";

foreach ( $movie as $key => $value ) {
echo "<dt>$key:</dt>";
echo "<dd>$value</dd>";
}

echo "</dl>";

?>

This script displays the following:

title:
    Rear Window
director:
    Alfred Hitchcock
year:
    1954
minutes:
    112

Altering element values

So far you’ve just looked at reading element values, but what if you want to change values as you loop through? You might try something like this:


<?php

foreach ( $myArray as $value ) {
$value = 123;
}

?>

However, if you do this you’ll find that your array values aren’t changed. This is because foreach works on a copy of the array values, rather than the original array. So the original array remains untouched.

To change array values, you need to reference the values. You do this by placing an ampersand (&) before the value variable in the foreach construct:


<?php

foreach ( $myArray as &$value ) {
$value = 123;
}

?>

$value then becomes a reference to the element value in the original array, which means you can change the element by assigning a new value to $value.

A reference is a pointer to the original value, rather than a copy of the value. It’s a bit like a shortcut in Windows, or an alias in Mac OS.

For example, the following script loops through each director in the $directors array, and uses PHP’s explode() function and list construct to reverse the director’s first and last names:


<?php

$directors = array( "Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang" );

// Change the name format for each element to "last, first"
foreach ( $directors as &$director ) {
list( $firstName, $lastName ) = explode( " ", $director );
$director = "$lastName, $firstName";
}

unset( $director );

// Output the final array
foreach ( $directors as $director ) {
echo $director . "<br />";
}
?>

This script outputs the following:
Hitchcock, Alfred
Kubrick, Stanley
Scorsese, Martin
Lang, Fritz

Notice that the script calls unset() to delete the $director variable after it’s been used as a reference in the first loop. This is always a good idea if you think you might want to use the variable later in the script in a different context.

If you don’t delete the reference then you run the risk of accidentally referencing the last element in the array (“Lang, Fritz”) when you next use the $director  variable, with often quite unexpected consequences!

Note: In case you’re wondering, you can only change array <em>values</em> in a foreach loop. You can’t change array keys

4 thoughts on “PHP BASIC PART-3 ( PHP Conditional Statement, Arrays and Array Functions )

  1. Thank you for every other magnificent post.

    Where else could anybody get that type of information in such
    an ideal approach of writing? I have a presentation next week, and I’m at the search for such information.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>