Home    Articles

 

Arrays in php ( use arrays dinamicaly ). Part 2.

 

In the previous article(part 1) we talk about basics usage of the arrays in php.
Now we will see how we can add data,travers the array in order to display values or get rid of some values.
With a loop i will add some data into my array.

<?php
  $n=4;
  $my_array = array();
  for($i=1;$i<=$n;$i++)
  {
    if($i==2)
    {
       $my_array[] = array();
       for($j=1;$j<=$n/2;$j++)
       {
         $my_array['two'][] = $j;
       }
    }
    else
    {
       $my_array[] = $i;
    }
  }
?>

This code will output something like this:

array
(
  [0]=>1
  [two]=> array
             (
               [0]=>1
               [1]=>2
             )
  [2]=>3
  [3]=>4
)

What we have done in the code is to add dinamicaly values, first loop will add values from 1 to 4. We also can see that our array will add automaticly keys in array.
The keys will begin from 0, the second loop will add in key [1] a new array with values from 1 to 2 (n/2).
This should be simple to understand.
Using foreach instrucion we can traverse the array until its last value even we don’t know exactly how many values our array have. Let’s see.

<?php
  //the $key variable,over the proccess will take all these values ("0","two","2","3")
  //the $value variable will become ("1","array","3","4")
  foreach($my_array as $key=>$value)
  {
    if($key == 'two')
    {
      foreach($value as $k=>$v)
      {
        echo $v."</br>";
      }
    } //end if
  }//end main foreach
?>

The code above will display the “1″ and “2″.
Now you saw how you can easily add values into arrays and display them.
You can use also unset function to delete a key from array, example: unset($my_array[$key]);

Arrays are more reliable to be used when you need to proccess a large amount of data.

Back to part 1

by