Tuesday, July 09, 2013

Arrays in PHP

Let's check out how PHP arrays work. Let's try with a very basic example ::

<?php
$arr = array( 1,2,3,4,5 );
print_r( $arr );
?>


PHP Array Index starts with 0. However we can specify an Index for any item explicitly while defining the array.

<?php
$arr = array( 10,20,30, 0=> 100,40,50 );
print_r( $arr );
?>


The above program puts 10 at index 0, then 20 at index 1, puts 30 at index 2 and then overwrites index 0 with 100. 40 and 50 are placed at index 3 and 4 respectively.

<?php
$arr = array( -9 => 10, 20, 30, 40=> 100, 40, 50 );
print_r( $arr );
?>


The program above starts with putting 10 at index -9. Next it puts 20 at index 0 and increments the index value for next items where the index is not defined explicitly. This way, value 20 and 30 are positioned at index 0 and 1. Next we explicitly define an index 40 and put a value 100 to it. And then we have a value 40 for which we don't define any index explicitly. Hence PHP would take the index of previous item 100 (index is 40 which is also the highest), add 1 to it (41) and set the value to that index. This way, value 40 and 50 are set to index 41 and 42 respectively.

If we want an array to start at index 1 instead of 0, we can write it the following way ::

<?php
$arr = array( 1 => 'Gimmy', 'John', 'Joseph', 'Jeff');

/// Or we can go the below way
$arr = array();
$arr[1] = 'Kim';
$arr [] = 'Tim';  // created index 2
$arr [] = 'Sim';  // 3
$arr [6] = 'Jim'; // 6
$arr [] = 'Lim';  // 7
?>


Iterating through such numerically indexed arrays would be as shown below :

<?php
$arr = array( 1,2,3,4,5,6,7,8,9 );

// Method 1
for($i = 0; $i< count($arr ); $i ++ ) echo $arr[$i];

// Method 2
foreach( $arr as $value ) echo $value;

// Method 2.1, to show the index => value pair
foreach( $arr as $index=>$value ) echo " [$index]=>$value, ";

// Bring the Array pointer at the first position
reset($arr);

// Method 3
while( list($index,$val) = each($arr) ) echo " [$index] => $val, ";

// Another method using next(), prev() etc functions
// At this point, the Array pointer is pointing to
// the end of the array, move it to the 1st position
reset( $arr );

// Move 2 places forward
next( $arr);
next( $arr);

// Print
echo current( $arr ); // 3

// Go 1 place backward
prev( $arr );

// Print
echo current( $arr ); //2
?>


The count() function returns total number of elements in the array. The each()  function returns each item in the array when used inside the loop. The current() function current item which the array pointer is pointing to.

Let's create an array of Odd numbers using range() function.

<?php
// Create array from 1 till 52, step 2
// Index starts at 0
$arr = range(1,52,2) ;
// Print
print_r( $arr );
?>


If we do not specify the step parameters with range() function, default 1 is taken.

Another way we can create an array of Odd numbers is shown below :
 

<?php
$arr = array();
for($i=1; $i<=52; $i = $i+2)
 $arr[] = $i; // Push to Array
?>

Notice that counter is increased by 2 in every iteration by the expression $i = $i + 2.

PHP Associative arrays are similar to numerically indexed arrays except the fact "index" and "value" pair are used as "named keys" and "value" pair. This means we can use any string as "index" (or key) of that array.

<?php
$arr = array( 'sky' => 'blue', 'sea' => 'green', 'snow' => 'white', 'tree' => 'green' );

// Print each Key=>Value pair
foreach( $arr as $element => $color )
 echo "<br>$element is $color";

// If we try to print the same array one more time
// we DONT need to move the pointer at the beginning
// But between 2 each($arr) calls, we must call reset()
foreach( $arr as $element => $color )
 echo "<br>$element is $color"; // This is OK

?>


If we try to print an index which is out of range, we get a notice saying "Undefined Index" or "Undefined offset" errcr. Check the example below..

<?php
$arr = array('banana' => 'yellow', 'mango' => 'green', 'strawberry' => 'red');
echo "{$arr['pineapple']}" ; // Undefined Index 'pineapple'
echo $arr[0];       // Undefined Offset 0

$arr = range(1,10); // Index 0 to 9
echo $arr[23];      // Undefined Offset 23
?>


Let's modify an array using loop.

<?php
$arr = range(1,10);

// Loop though, increment each value by 1
for($i=0;$i<count($arr);$i++) 
  $arr[$i]++;

// Foreach works with a copy of the original
// Array, hence it can not modify the content
// However the each() function works with the original
// copy of the array. Hence as a result, all elements
// would be multiplied by 2
while(list($key,$value) = each($arr) )
 $arr[$key] = $value * 2;
?>


Let's try some other type of for and while loop construct to print the elements of various arrays.

<?php
$arr = range( 1, 10 );

// Indexed/Associative Array - While Construct - I
$i = 0;
while( $i++ < count($arr) )
{
  // print
  echo "<br>" . key( $arr ) . " : " . current( $arr );
  // Move to Next Item
  next( $arr );
}

// Indexed Array - While Construct - II
while( 1 )
{
  echo "<br>" . key($arr) . " : " . current( $arr );
  next( $arr );
  if( key($arr) === null ) break;
}

/// Associative Arrays
$arr = array('banana' => 'yellow', 'mango' => 'green', 'strawberry' => 'red');

/// Associative Array - For Construct - I
for( reset($arr); key($arr); next($arr) )
{
  /// print banana : yellow etc
  echo "<br>" . key( $arr ) . " : " . current( $arr );
}

?>

Let's try some functions like isset(), empty() on PHP arrays.

<?php
$arr = "";
$arr2 = array();


// Prints nothing as False
echo is_array( $arr );

// Prints 1 as True
echo empty( $arr2 );

// Prints 1 as True
echo isset($arr2);
?>


The $_GET or $_REQUEST or $_POST variables are associative arrays of variables passed to the current script.

We can test if any variable is set in those arrays. This is shown below ..


<?php
 

if( isset( $_GET['fname'] )  )
{
  //
This part gets executed if URL is like
  // test.php?fname=
}

if( isset( $_GET['fname'] )  && trim( $_GET['fname'] ) != '' )
{
  //
This part gets executed if URL is like
  // test.php?fname=john
}

?>


If 'fname' word is present in the URL, then both the if conditions become true. However, if a valid value for fname is submitted, then only the second If condition satisfies.

To delete any item from an array, we use unset() function as shown in the program below.


<?php
$arr = range(10,20);
unset( $arr[4] ); //
4th Index is deleted
unset( $arr[5] ); // 5th Index is removed
unset( $arr[6] ); // 6th Index is removed

$arr = array( 'sky' => 'blue', 'sea' => 'green', 'snow' => 'white', 'tree' => 'green' );
unset( $arr['sky'], $arr['sea'] ); //
Item with key 'sky', 'sea' removed
?>


The above program removes 3 items from index 4,5 and 6. However, old index => value combination is maintained. That means, after we delete the 4th index from the array, the element at index 5 is not re-positioned at index 4. This behaviour occurs in JavaScript when we try to remove selected items from a selectbox which was discussed in article "HTML Select element manipulation using Javascript - II".

After deleting indexes from an array, holes are actually created and hence the array can not be looped through using for() normal loop construct. We need to use foreach() construct in such cases. 


Another important thing to remember, when we use unset() to remove array items, the index stays at where it was before. It does not decrease automatically. Check the example below : 

<?php
// Create the array
$arr[0] = 0; $arr[1] = 1;

// Unset the elements
unset($arr[0]); unset($arr[1]);

// Add new elements at index 2
$arr[] = 2;
?>

The last statement would insert the value '2' at the index '2'. It does not decrease when we unset elements from the array.

Check more on Arrays in my next article Arrays in PHP - 2

No comments: