Home    Articles

 

Arrays in php (declare,add values,display values). Part 1.

 

What exactly arrays are?
Arrays are special variables that can hold more values at a time, let’s see a simple example.
The code bellow will declare an empty array.

<?php
  $our_variable = array();
?>

In this variable we can hold large amount of values. Let’s assume that we want to use some data about one user likenameage,address,phone number
This is how we will add keys to array and values to our keys from array.

<?php
  //Instead of using multiple variables
  $user_name = "Jhon";
  $user_age  = "27";
 // $user_address = "...
 // $user_ etc.....
  //we declare our variable as array (empty, in this way you can reset your variable)
  $our_variable = array();
  //now we add keys to array and values. The php knows that you want to add "name" key and for this key "Jhon" value.
  //doesn't need to be predeclared.
  $our_variable['name'] = 'Jhon';
  $our_variable['age'] = '27';
  $our_variable['address'] = 'NYC';
  $our_variable['phone'] = '555-555';
  //now let's display some values
  echo $our_variable['name']." has ".$our_variable['age']."years old and lives in ".$our_variable['address'];
  // the code above will display "Jhon has 27 years old and lives in NYC"   
?>

This is an awesome way to store data, no?
But, how if this “Jhon” has not one but two phone numbers?
Then we need to asign in $our_variable at key phone not a value but a new array.
Now we can store more and more data. Don’t forget the code above. We will modify only the line$our_variable['phone'] = ’555-555′;

<?php
  //the line $our_variable['phone'] = '555-555'; becomes
  $our_variable['phone'] = array('primary'=>'555-555',
                                 'secondary'=>'444-444'
                                 );
  //now you saw how to declare and use array ongoing.
  //let's display some data
  echo "The primary phone of our ".$our_variable['name']." is ".$our_variable['phone']['primary']." and its second phone number is ".$our_variable['phone']['secondary'];
  //the code above will display "The primary phone of our Jhon is 555-555 and its second phone number is 444-444"
?>

Now we used Associative arrays ( becouse have named keys ) and Multidimensional arrays( becouse it contains one or more arrays inside of the main array)
In next part we will see how to use Indexed arrays that use numbers as keys.

Next to part 2

by