PHP Arrays

An array stores multiple values in one single variable:

What is an Array?

An array is a special variable, which can hold more than one value at a time.
An array can hold many values under a single name, and you can access the values by referring to an index number.

Create an Array in PHP

the array() function is used to create an array:

array();

there are three types of arrays:
  1. Indexed arrays - Arrays with numeric index
  2. Associative arrays - Arrays with named keys
  3. Multidimensional arrays - Arrays containing one or more arrays

PHP Indexed Arrays :

There are two ways to create indexed arrays:
          $alphabet=array("A","B","C");
The index can be assigned automatically.


           $alphabet[0]="A";
           $alphabet[1]="B";
           $alphabet[2]="C";
the index can be assigned manually:

Example :

<?php
     $alphabet=array("A","B","C");
      echo  $alphabet[0] . ", " . $alphabet[1] . " , " . $alphabet[2] . ".";
?>

The count() function is used to return the length (the number of elements) of an array:

Example : 

<?php
   $alphabet=array("A","B","C");
   echo count($alphabet);
?>

print all the values of an Indexed array :

Example :

<?php
$alphabet=array("A","B","C");
$arrlength=count($alphabet);
for($x=0;$x<$arrlength;$x++)
  {
  echo $alphabet[$x];
  
  }
?>


PHP Associative Arrays :


Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array: 

Example :
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
Or
$age['Peter']="35";
$age['Ben']="37";

$age['Joe']="43";

print all the values of an associative array :

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

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

array can also contain another array as a value, which in turn can hold other arrays as well. In such a way we can create two- or three-dimensional arrays.

Example :
<?php
// A two-dimensional array:
      $cars = array
       (
           array("Volvo",100,96),
           array("BMW",60,59),
           array("Toyota",110,100)
      );
?>

In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on.

Automatically Assigned ID keys :

$families = array
  (
  "Griffin"=>array
  (
  "Peter",
  "Lois",
  "Megan"
  ),
  "Quagmire"=>array
  (
  "Glenn"
  ),
  "Brown"=>array
  (
  "Cleveland",
  "Loretta",
  "Junior"
  )
  );

Print Value :-
echo "Is " . $families['Griffin'][2] . 
" a part of the Griffin family?";

OUT PUT - 
Is Megan a part of the Griffin family?

Comments