Skip Navigation Links
EZWEB
PHPExpand PHP

PHP Arrays

Creating

  • Unlike strings, which hold a single value, arrays hold a list of values, also called elements. Each value can be a string, number, or another array.
  • Arrays are structured as a list of key-value pairs – for each value in the list, there is a key or index associated with it.

PHP supports 2 kinds of arrays:

  • Indexed arrays: use numbers as the keys, beginning at zero
  • Associative arrays: use associated strings as keys

 

Indexed Arrays

  • To create an array use the array( ) function:
  • Here is an array of people who represent a wide variety of political philosophies:

  $parties = array( “Kennedy”, “Bush”, “Perot”, “Demento”, “Hoffman”, “Maharishi” );

  • Other ways to create arrays include:
    • copying one array to another
    • using the range( ) function to create a sequential array of numbers or letters:
      $days = range( 1, 31);
      $years = range( 2003, 2013 );
      $alphabet = range( a, z );
    • populate the array directly from a text file
    • populate the array directly from a database

We can also create each element separately:
   $parties[ 0 ] = ‘Kennedy’;
  $parties[ 1 ] = ‘Bush’;
  $parties[ 2 ] = ‘Perot’;
  $parties[ 3 ] = ‘Demento’;
  $parties[ 4 ] = ‘Hoffman’;
  $parties[ 5 ] = ‘Maharishi’;

  • To access individual elements use the index number of the element within brackets after the name of the array:

echo “$parties[ 4 ]”; //will print the name “Hoffman”

  • In some instances, and with some versions of PHP, if you have trouble printing the element from inside double quotes, just leave the quotes off and concatenate the element with whatever text you are printing:

 

echo “The leader of the Hippy Party was “ . $parties[4] . “.”;

  • or surround the reference to the array with curly brackets:

 

 echo “The leader of the Hippy Party was {$parties[ 4 ]}.”;

  • One way to access all the elements on an indexed array is with a while or for loop:

 

     for( $x = 0; $x < count( $parties ); $x++ ){
       echo “{$parties[ $x ]} <br />”;
  }

  • If you want your array to start at an index other than zero, use the following syntax. Subsequent values will be numbered incrementally.

 

$months = array( 1 => ‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’,
‘September’, ‘October’, ‘November’, ‘December’ );

Associative Arrays

  • With an indexed array, we allow PHP to assign a default index number. With an associative array we can associate any word, phrase, or index with a particular value. To create an associative array we use the following syntax. We will associate the names with the political affiliation they are associated with:

  $parties = array(     ‘Democratic’ => ‘Kennedy’,
‘Republican’ => ‘Bush’,
‘Reform’ => ‘Perot’,
‘Libertarian’ => ‘Demento’,
‘Hippy’ => ‘Hoffman’,
‘Natural Law’ => ‘Maharishi’
 );

  • White space in this case does not matter – using this format makes everything easier to read. The first word in the associative pair is known as the key, the second as the value. This has implications, if you think about it, because information in forms is sent as name=value pairs, or key=value pairs.

 

  • Now to access a particular value we use the key rather than the index number. If we want to print the name “Hoffman” we use:

          echo $parties[ ‘Hippy’  ];   // case sensitive

Adding Items to an array

  • You can add additional elements to an array with the assignment operator, the = sign. To add elements to an indexed array make a simple assignment:

     $parties[ ] = “Cleaver”;

  • This adds the value to the next available index in the array.  To add an element to an associative array, make a similar assignment using the key:

  $parties[ “Peace and Freedom” ] = “Cleaver”;

Counting elements in an array

  • To find the number of elements in an array use the count( ) or the sizeof( ) function. Both return the number of elements in the passed array.

            $numOfElements = count( $parties );

  • In this example, after adding the last element, we would get a value of 7.
  • One other function, array_count_values( ) is more complex.
    • It counts how many times each unique value occurs in an array.
    • The function returns an associative array containing the frequency of each value.
    • The keys in this second array are the unique values in the original array, the values in the second array contain the number of instances of the corresponding key. EG:

$array1 = (‘Roy, ‘Bob’, Bubba’, ‘Bob’, ‘Levi’, ‘Bob’ );
$array2 = array_count_values( $array1 );

  • returns the associative array:

$array2 = ( ‘Roy’ => 1,‘Bob’ => 3,‘Bubba’ => 1,‘Levi’ => 1 );

Printing

  • Let’s look at different ways to print an array. What happens if we try to print the array using the variable name?

  echo “$parties”;
  echo “<br />$numOfElements”;

  • When you try to use an array without pulling out individual values, what is returned is the string “Array”, meaning that you need to separate it into its individual elements.
  • However, we have a number of different ways to iterate through an array. As mentioned earlier, there are a couple more looping structures which work with arrays.


each( )

  • One way to access all the values of an array is to use a loop with the each( ) construct.
  • each( ) creates a second array, which holds each of the key / value pairs of the original array.
    • So we have two arrays we are working with now: the original array, the one we are traversing, and the array that each( ) returns each time it is called (which contains the current element and its key/index).
  • The array that each( ) returns has 4 key = value pairs:

                 Key: 0,  Value: current key
       Key: 1,  Value: current value
       Key: ‘key’,  Value: current key
       Key: ‘value’,  Value: current value

  • Let’s look at the code:

  for( $n = 0; $n < count( $parties ); $n++ )
  {
      $myPair = each( $parties );
      print “Key: $myPair[ ‘value’ ]  belongs to the $myPair[ ‘key’ ]   Party.<br />”;
            // or you can print                               
      print “Key: $myPair[ 1 ]  belongs to the $myPair[ 0 ]  Party.<br />”;
  }

  • Using our example, then, the first time through, the for statement would return the following, assigned to $myPair:

                 Key: 0,  Value: Democrat
       Key: 1,  Value: Kennedy
       Key: ‘key’,  Value: Democrat
       Key: ‘value’,  Value: Kennedy

  • and the array would look like:

  $myPair = array(   “0” => “Democrat”,
“1” => “Kennedy”,
“key” => “Democrat”,
“value” => “Kennedy”,
);

  • So now we can print the values of the original array by using:

  echo “$myPair[ ‘value’ ]”;

  • Every array has an internal pointer that points to the current element in the array.
    • Each time the for counter runs, the each( ) function uses that pointer to point to the next key = value pair in the original array. each( ) then continues to run until it runs through the complete array.
  • One significant thing about the each( ) construct – if you want to use the same array twice in one script, you have to reset the array’s internal pointer to the beginning.
    • As you use the each( ) function the first time, it points to each successive element.
    • The first time thorough, when it reaches the end of the array, the pointer stays at the end.
    • Using reset( ) sets the current element back to the start of the array.

       reset( $parties );


each( ) and list( )

  • Remember, each( ) returns a second array of the current element and its key/index. Placed within a while loop, we can run through each element in the original array, and return the second array.
  • The list( ) function splits an array into a number of values. We can separate the smaller array returned by the each( ) function and automatically assign them to variable names:

while( list( $partyName, $leaderName ) = each( $parties ) )
{
   echo “$leaderName is a member of the $partyName Party.”;
}

foreach( )

  • One of the fastest and easiest ways to access all the values of an array is to use the foreach( ) construct.
  • Beginning with PHP4, we have a foreach construct available, which iterates through each element of an array.
  • There are two ways to do it:
  • The first way pulls out only the values in the array.
  • In this example each time the loop iterates, the value of the element is assigned to $value.
  • You can use whatever variable name you want.

  foreach( $arrayName as $value ) {
           statements;
  }
      
EG:
  foreach( $parties as $value ) }
           echo “$value <br>”;
  }

  • The second way also loops through the array.
    • On each loop, the value of the current element is assigned to $value, and its key is assigned to $key.
    • Then the pointer is moved to the next element.

  foreach( $arrayName as $key => $value ) {
           statements
  }

EG:
  foreach( $parties as $key => $value ) }
       echo “$value belongs to the $key Party. <br>”;
  }

print_r( ) //  displays human-readable information about       
           //a variable

  • If given a string or number, it will print the actual value.
  • If given an array, will print in a format that shows keys and values.

$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x','y','z'));
print_r ($a);

will output

Array
(
    [a] => apple
    [b] => banana
    [c] => Array
    (
        [0] => x
        [1] => y
        [2] => z
    )
)

Multi-Dimensional Arrays

  • Arrays are useful because they can hold a great deal of information.
  • You can also use multi-dimensional arrays which can hold even more information.
  • Instead of holding simple strings or numbers as we have been doing, we can create an array which holds other arrays as values.

EG:
$monday = array( “Chicken Rice”, “Chili”, “French Onion”, “Barley”, “Bean” );
$tuesday=array("Rivel", "Tomato", "Wedding", "Vegetable", "Okra");
$wednesday=array("Turkey Noodle", "Bean Bacon", "Potato", "Beef Barley", "Meatball");
$thursday=array("Chicken Noodle", "Garlic", "Pumpkin", "Clam Chowder", "Spam");
$friday=array("Turkey Rice", "Mushroom", "Fruit Bat", "Dumpling", "Vegetarian Chili");

$soupsOfTheDay = array( “Monday” => $monday,
            “Tuesday” => $tuesday,
            “Wednesday” => $wednesday,
            “Thursday” => $thursday,
            “Friday” => $friday
            );

  • Multidimensional arrays work very similar to regular arrays, except that each element has two indices rather than one.
  • Pointing to a value in one of the secondary arrays requires thought.

If we print
  print $soupsOfTheDay[ ‘Monday’ ];
what is going to print on the screen?
  Array

  • To access an element within the $monday array we add a second index to the statement:

  print $soupsOfTheDay[ ‘Monday’ ] [ 0 ];
will print the value
  Chicken Rice

  • So, here’s what happens: 
    • First, you point to an element (which happens to be an array) in the primary $soupsOfTheDay array, using the key  ( $soupsOfTheDay[  ‘Monday’ ] ).
    • Then you point to an element in the secondary array using the index number ( $soupsOfTheDay[ ‘Monday’ ] [ 0 ] ).
    • You can also use the key name instead of an index number if you have it set up that way.
  • Just a reminder, but some versions of php don’t allow you to print directly using the above syntax.

  print  $soupsOfTheDay[  ‘Monday’ ] [ 0 ] ;

  • Instead you may have to use curly brackets:

     print { $soupsOfTheDay[  ‘Monday’ ] [ 0 ] };

How can we print all of the soups for Monday using a for or while statement?
     for( $x = 0; $x < count( $monday ); $x++ ){
       echo “{ $soupsOfTheDay[  ‘$monday’ ] [ $x ] }”;
  }

  • How do we print all 5 soups for all 5 days, ie, the content of all the arrays, using a foreach( ) loop?

 

  foreach($soupsOfTheDay as $key => $value){  // in this line $value is an array
     print "<br><b>$key</b><br>";

       for($x=0;$x<count($soupsOfTheDay[$key]);$x++){
       print "{$soupsOfTheDay[$key][$x]}<br>";
       }
  }

  • Oftentimes, multidimensional arrays are represented as a table.
  • In this example, the first column represents the key from the primary array, while the first row represents the index of the secondary arrays.

 

0

1

2

3

4

Monday

Chicken Rice

Chili

French Onion

Barley

Bean

Tuesday

Rivel

Tomato

Wedding

Vegetable

Okra

Wednesday

Turkey Noodle

Bean Bacon

Potato

Beef Barley

Meatball

Thursday

Chicken Noodle

Garlic

Pumpkin

Clam Chowder

Spam

Friday

Turkey Rice

Mushroom

Fruit Bat

Dumpling

Vegetarian Chili

  • Again, each element is referenced by two indices, a row and a column. In this example, the indices are a key and an index number.
  • Multidimensional arrays can use only index numbers

       $arrayName[ 2 ] [ 3 ];

or only keys

                 $arrayName[ ‘key1’ ] [ ‘key2’ ];

  • or, as in this example, a combination of keys and index numbers.
  • If you use only index numbers you can use a simple for loop to iterate through the array. If you use keys, however, you use a foreach( ) or each( ) loops. 
  • When using multidimensional arrays, you do not need to stop at 2 dimensions. Those secondary arrays can contain a third level of arrays, and those arrays can even contain more arrays. Once you get beyond three levels, however, it gets pretty hard to keep track of.
  • A three-dimension array would have rows and columns like the previous table example, but it would also have depth, containing more than one table. The syntax to access an element would look like this:

$calendar = array( “January” => $jan,
           “February” => $feb,
           “March” => $mar  );

$jan = array( 1 => $jan_1, $jan_2, $jan_3 );

$jan_1 = array( “sleep in", “watch football” );
$jan_2 = array( “ski” );
$jan_3 = array( “return to work”, “mope” );

 

       $calendar[ ‘January’ ] [ 3 ] [ 0 ];

End PHP Arryas





Free Tutorials and Training