PHP array Function -array()

PHP array  Function is used to create new arrays.

For  example:

Below example create array called animals and assign its 3 elements.All the elements are printed using  echo function.

<?php

$animals=array("Goat","Cow","Sheep");

echo "I like " . $animals[0] . ", " . $animals[1] . " and " . $animals[2] . ".";

?>

As  i stated earlier in my post about PHP Arrays,there are three types of arrays.Namely

  • Indexed arrays – these are arrays with only one key or one index
  • Associative arrays – These are arrays that contain named
  • Multidimensional arrays – These are arrays that have more than one array inside them.

PHP array Function

Syntax used to create indexed arrays:

array(val1,val2,val3,etc.);

Syntax used to create associative arrays:

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

Examples

1.How to Create associative array called Marks;

<?php

$marks=array("Peter"=>"35","Eric"=>"37","John"=>"43");

echo "Peter is " . $marks['Peter'] . " years old.";

?>

Example 2

How to loop through a indexed array,get the values and print them.

<?php

$animals=array("Goat ","Cow","Donkey");

$arrlength=count($animals);

 

for($x=0;$x<$arrlength;$x++)

{

echo $animals[$x];

echo "<br>";

}

?>

Example 3

Below example shows how one can loop through values contained in associative array,get their values and print them.

<?php

$marks=array("Jessica"=>"35","Eric"=>"37","John"=>"43");

 

foreach($marks as $y=>$y_value)

{

echo "Key=" . $y . ", Values=" . $y_value;

echo "<br>";

}

?>

Example 4

How to create a multidimensional array

<?php

// A two-dimensional array:

$marks=array

(

array("Eric",100,96),

array("John",60,59),

array("Mellisa",110,100)

);

?>

See Complete  Array Functions :PHP Array Functions

About the Author: Eric K

Kenyan Developer and Blogger with Interests in Java,Javascript,Node.js, Wordpress, Android, PHP and Making Money Online. Solving world problems through programming is my passion. Hire me: Email : kawi3462@gmail.com