PHP Arrays

PHP Arrays

  • An array is a special variable.
  • Hold more than one value at a time under a single name, 
  • Stores multiple values in one single variable. 
  • Secondary data type. 
  • access the values by referring to an index number.

The array can create by two methods 

1. By squire bracket [], 

2. By array constructor “ ”. 

ex. $array_name[ ] = " ";

Syntax

Syntax for indexed arrays:

array(value1, value2, value3)

$A = array(12,23,24,6,8)

Syntax for associative arrays: 

array(key=>value, key=>value, key=>value, etc.)


Key:- Specifies the key (numeric or string).

Value:- Specifies the value.

Ex.

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

Ex.

<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);

for($x=0;$x<$arrlength;$x++)
  {
  echo $cars[$x];
  echo "<br>";
  }
?>

Ex.

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

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

Ex.

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

In PHP, the array() function is used to create an array:

array();


Note:

A short array syntax exists which replaces array() with [].


// Using the short array syntax
$array = [
    "foo" => "bar",
    "bar" => "foo",
];

For viewing array structure then we use print_r($array_Names);

By default Array index start from 0 to n-1 (max size – 1).

<?php

$empNames[] = "ram";

$empNames[] = "mohan";

$empNames[] = "Devi";

print_r($empNames);

?>

//Output:

Array

(

[0] => ram

[1] => mohan

[2] => Devi

)


<?php

$eNames = array("Raju", "Mahi", "Manu");

print_r ($eNames);

?>

Array

(

[0] => Raju

[1] => Mahi

[2] => Manu

)

Types of arrays:

1. Numeric array − An array with a numeric index. Values are stored and accessed in linear fashion.

2. Associative array − An array with strings as an index. Stores element values in association with key values rather than in strict linear index order.

3. Multidimensional array − An array containing one or more arrays and values are accessed using multiple indices


Numeric Array

  • Store numbers, strings, and any object but their index will be represented by numbers. 
  • By default array index starts from zero.

Traversing

  • Traverse an indexed array using loops in PHP. 
  • Loop through the indexed array in two ways. 
  • First by using for loop and secondly by using foreach.

Example

Create and access numeric arrays:-


<html>


   <body>

      <?php

         /* First method to create array. */

         $numbers = array( 1, 2, 3, 4, 5);

         foreach( $numbers as $value ) {

           echo "Value is $value <br />";

     }

         /* Second method to create array. */

         $numbers[0] = "one";

         $numbers[1] = "two";

         $numbers[2] = "three";

         $numbers[3] = "four";

         $numbers[4] = "five";

        foreach( $numbers as $value ) {

            echo "Value is $value <br />";

         }

      ?>

   </body>

</html>

 result −


Value is 1 

Value is 2 

Value is 3 

Value is 4 

Value is 5 

Value is one 

Value is two 

Value is three 

Value is four 

Value is five 


Associative Arrays

These are very similar to numeric arrays as functionality but they are different in terms of their index. 


Their index as string so establishes a strong association between key and values.


NOTE − Don't keep associative array inside double quote while printing otherwise it would not return any value.


Traversing Associative Arrays: 


A similar way as numeric arrays using loops. 


Use loop in two ways. 


First by using for loop. 


Secondly by using foreach.


Example

<html>

   <body>

    <?php

         /* First method to associate create array. */

         $salaries = array("mohan" => 2000, "rama" => 1000, "ramesh" => 500);

         echo "Salary of mohan is ". $salaries[‘mohan’] . "<br />";

         echo "Salary of rama is ".  $salaries[' rama ']. "<br />";

         echo "Salary of ramesh is ".  $salaries[' ramesh ']. "<br />";

         /* Second method to create array. */

         $salaries[' mohan '] = "high";

         $salaries[' rama '] = "medium";

         $salaries[' ramesh '] = "low";

         echo "Salary of mohan is ". $salaries[' mohan '] . "<br />";

         echo "Salary of rama is ".  $salaries[' rama ']. "<br />";

         echo "Salary of ramesh is ".  $salaries[' ramesh ']. "<br />";

      ?>

   </body>

</html>

Result −


Salary of mohan is 2000

Salary of rama is 1000

Salary of ramesh is 500

Salary of mohan is high

Salary of rama is medium

Salary of ramesh is low


Multidimensional Arrays

In a multi-dimensional array, each element in the main array can also be an array. 

each element in the sub-array can be an array, and so on. 

Values are accessed using multiple indexes.



Traversing Multidimensional Arrays: 


Traverse through the multidimensional array using for and foreach loop in a nested way. 

One for loop for the outer array and one for loop for the inner array.


Example

wap for create a two dimensional array to store marks of three students in three subjects −


<html>

  <body>

      <?php

         $marks = array( 

            "mohammad" => array (

              "physics" => 35,

               "maths" => 30,        

               "chemistry" => 39

            ),

            "qadir" => array (

               "physics" => 30,

               "maths" => 32,

               "chemistry" => 29

            ),

            "zara" => array (

               "physics" => 31,

               "maths" => 22,

               "chemistry" => 39

            )

         );

         /* Accessing multi-dimensional array values */

         echo "Marks for mohammad in physics : " ;

         echo $marks['mohammad']['physics'] . "<br />"; 

         echo "Marks for qadir in maths : ";

         echo $marks['qadir']['maths'] . "<br />"; 

         echo "Marks for zara in chemistry : " ;

        echo $marks['zara']['chemistry'] . "<br />"; 

      ?>

   </body>

</html>

Result −


Marks for mohammad in physics : 35

Marks for qadir in maths : 32

Marks for zara in chemistry : 39


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


Ex.


<?php

$cars = array("Volvo", "BMW", "Toyota");

echo count($cars);

?>


Post a Comment

0 Comments