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 notin_array($needle, $haystack, $strict)-- a useful function to check for the existence of a value$needlein array$haystack. The third parameter$strict, when set to true, will also ensure that the value stored in$haystackis the same type as the search value$needle. The default value for the$strictparameter is false.count($val)-- This returns the number of elements contained within an array. Note that in the event that$valis not a valid PHP variable, it will return a value of "0" instead of causing an error. It is recommended thatis_array()be called prior tocount()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.
Showing messages 1 through 2 of 2.
-
How to Append indexed multiple data into existing arrays?
2004-08-24 12:49:12 jeanloui [View]
-
thanx,a nd a hard question with array's
2002-12-23 10:54:41 anonymous2 [View]
I want to thank you for this article, i'm making a script for logging visitors, but I also want to know the way they follow through the site, and that's the problem.
This is the function I have made til now, it works but it only tells me which pages are under volgnr 1, volgnr 2 etc. I want to show things like this:
page1-page 2-page3
|_page 5-page 6
but now I get
volgnr1
-page 1
volgnr2
-page 2
-page 5
volgnr3
-page 3
-page 6
This is the code:
<?PHP
function pageroute($aantalpaginas){
/* functie in testfase voor een verzameling van de hits om zo de paginaroutes te bepalen die de bezoekers volgen door de site. */
/* de array vullen met de gegevens uit de database, werkt correct voor zover getest */
/* Alle unieke bezoekers ophalen uit de db */
$sql="SELECT id FROM bezoekers";
$result = mysql_query($sql);
/* voor alle unieke bezoekers de hits ophalen */
while ($row = mysql_fetch_object($result)){
$hitsql="SELECT page, volgnr FROM hits WHERE user='".$row->id."' ORDER BY volgnr ASC";
$hitresult = mysql_query($hitsql);
/* alle hits in volgorde in de array plaatsen */
while ($hitrow = mysql_fetch_object($hitresult)){
$route[$hitrow->volgnr][]=$hitrow->page;
}
}
$nivo=1;
foreach ($route AS $key => $array)
{
echo 'Stap: '.$key.'
';
foreach (array_count_values($array) AS $page => $count)
{
echo '|_page:'.$page.'('. $count.'x)
';
}
echo "
\n";
}
}
?>
volgnr=follownumber (dutch)
If you have an idea please mail me at dj_lucv@hotmail.com







I have this simple array:
---------------
And I would like to append new nested indexed with multiple data into the same array, but into a new index as:
---------------
If I write (after the array creation) for append:
...it gives me only:
.... adding the new index but ONLY ONE value: [0] => "pepito" into the new array index....
But I need the multiple data [0], [1], [2], etc. into new_index insertion...!
What is the syntaxis for appending new indexes with multiple data into arrays?
Thanks!