PHP 5 Arrays: How to use PHP Array

PHP Array : An array allows to record values in the same variable.

Example:

<?php
$name= array(“Bob”, “Aliks”, “Sara”);
echo “I like ” . $name[0] . “, ” . $name[1] . ” and ” . $name[2] . “.”;
?>

What is an Array?

An Array allows to store several values under the same name, it is a special variable.

If you have a list of items (a list of person names, for example), storing the names in our array could look like this:

$name= “Bob”;
$name= “Aliks”;
$name= “Sara”;

 

Now, if one wants to find a person among several people then how to do it? What if you have 100 people?

The solution is to create an array!

An array can store many values under a same and single name. If you want to access  a value you can use an index number.

Create an Array in PHP

In PHP, if you want to create an array you can use  the array() function:

array();

We have three types of arrays in PHP:

  • Indexed arrays – Arrays with a numeric index
  • Associative arrays – Arrays with named keys
  • Multidimensional arrays – Arrays containing one or more arrays

PHP Indexed Arrays

I you want to create indexed arrays, there are two ways :

Automatically: The index can be assigned automatically, the syntaxe is:

$name= array(“Bob”, “Aliks”, “Sara”);

Or manually like this:

$name[0]= “Bob”;
$name[1]= “Aliks”;
$name[2]= “Sara”;

In the following example we create an indexed array named $name, assigns (automatically) 3 elements in the array and then print array contents :

Example:

<?php
$name= array(“Bob”, “Aliks”, “Sara”);
echo “My friends are:  ” . $name[0] . “, ” . $name[1] . ” and ” . $name[2] . “.”;
?>

 

Get The Length of an Array – The count() Function

If you want to print the length of an array(the number of elements), you can use count() function :

Example

<?php
$name= array(“bob”, “aliks”, “sara”);
echo count($name);
?>

Loop Through an Indexed Array

We can use a for loop to loop through and print all the content of an array like this example:

<?php
$name= array(“bob”, “aliks”, “sara”);
$arrlength = count($name);

for($i = 0; $i < $arrlength; $i++) {
echo $name[$i];
echo “<br>”;
}
?>

PHP Associative Arrays

If you use named keys that you assign to arrays so this is associative arrays

There are 2 methods to create an associative array:

$age = array(“bob”=>”25”, “Aliks”=>”45”, “sara”=>”18”);

or this way:

$age[‘bob’] = “25”;
$age[‘Aliks’] = “45”;
$age[‘sara’] = “18”;

We can us named keys in a script:

Example

<?php
$age = array(“bob”=>”25”, “Aliks”=>”45”, “sara”=>”18”);
echo “Bob is ” . $age[‘bob’] . ” years old.”;
?>

Loop Through an Associative Array

If you want to print all values of an associative array, follow this way:

<?php
$age = array(“bob”=>”25”, “aliks”=>”45”, “sara”=>”18”);

foreach($age as $x => $x_value) {
echo “Key=” . $x . “, Value=” . $x_value;
echo “<br>”;
}
?>

Multidimensional Arrays