PHP DevCenter
oreilly.comSafari Books Online.Conferences.

advertisement


Arrays in PHP: Part 2
Pages: 1, 2

Useful array functions

Here are some useful functions to get you started working with arrays:



  • is_array($val) -- This is useful for testing if a variable is actually an array or not. It will return the value of "true" if the passed value is an array, "false" if it is not

  • in_array($needle, $haystack, $strict) -- a useful function to check for the existence of a value $needle in array $haystack. The third parameter $strict, when set to true, will also ensure that the value stored in $haystack is the same type as the search value $needle. The default value for the $strict parameter is false.

  • count($val) -- This returns the number of elements contained within an array. Note that in the event that $val is not a valid PHP variable, it will return a value of "0" instead of causing an error. It is recommended that is_array() be called prior to count() to ensure that the return value reflects the true nature of the variable being checked.

For full documentation on these functions and examples of their use, please consult the PHP manual.

A new control structure: foreach

Of all of the control structures available to developers in PHP, foreach is the only one specifically for use with arrays. In functionality, it is very similar to the for statement but doesn't look much like one in syntax. Its purpose is to provide a quick and easy way for developers to traverse the contents of an array (both integer indexed and associative) and process each element within the array. For example, let's say you have an integer-indexed array with an unknown number of elements that you would like to print the values for. This can be accomplished of course through the use of the for statement and our newly-found count() statement as shown below:

<?php
  for($i = 0; $i < count($myarray); $i++) {
    echo $myarray[$i];
  }
?>

There is nothing wrong with this style. However, what if the array was an associative array rather than integer-based? In such circumstances, complex while statements coupled with at least two more functions could produce the same results however we have a better solution: the foreach statement. The syntax for the foreach statement is as follows:

foreach($array_val as [$key_val =>] $value) {
	...
}

It also has a syntax simliar to the for() endfor; syntax:

foreach($array_val as [$key_val =>] $value):
   ...
endforeach;

where $array_val is the array, $key_val is the variable assigned to store the current index, and $value stores the actual value associated with that index.

How it works

Let's consider the following two samples of the foreach statement:

<?php
  $myarray = array("foo"=>"bar",
                       0=>5,
              "mynumber"=>12e3);
  foreach($myarray as $value) {
    echo "The value is $value<br />";
  }
  echo "<br />";
  foreach($myarray as $key=>$value) {
    echo "The value of index $key is $value<br />";
  }
?>

In this code fragment, we create a simple array $myarray that has three values in it. The first is a string-based key "foo" with a value of "bar", the second is a integer-based key of 0 with a value of 5, and the third is a string-based key of "mynumber" with a value of "12e3" (or 12,000 in standard notation). We then use both syntaxes of the foreach statement and echo the results. When this script is executed, we'll get the following output:

The value is bar
The value is 5
The value is 12000
The value of index foo is bar
The value of index 0 is 5
The value of index mynumber is 12000

When we compare the two foreach statement outputs, we can see that both of them traversed the entire array and stored the value stored at each index of the array in the variable $value which we then output to the screen.

In the second foreach statement however, we specified a variable to be used to store the value of the index as well as the value at that index. The result was we were able to not only traverse the array for all of its values, but also retrieve and maintain the association between the indexes of those values. This is a very powerful and useful tool when dealing with arrays that will allow you to quickly and easily process each individual item within any type of array regardless of its type of index. It is strongly recommended that the foreach statement be used in all array traversals (instead of a for loop).

Note: Although we used the values $key and $value in our foreach example, the variable names themselves can be any valid variable name within PHP (provided of course that it is not being used elsewhere in your script).

John Coggeshall is a a PHP consultant and author who started losing sleep over PHP around five years ago.


Read more PHP Foundations columns.

Return to the PHP DevCenter.


Valuable Online Certification Training

Online Certification for Your Career
Earn a Certificate for Professional Development from the University of Illinois Office of Continuing Education upon completion of each online certificate program.

PHP/SQL Programming Certificate — The PHP/SQL Programming Certificate series is comprised of four courses covering beginning to advanced PHP programming, beginning to advanced database programming using the SQL language, database theory, and integrated Web 2.0 programming using PHP and SQL on the Unix/Linux mySQL platform.

Enroll today!


Sponsored by: