Search

PHP Arrays

An array is a special variable, which can hold more than one value at a time.If you have a list of items (a list of mobile names, for example), storing the mobile in single variable could look like this

$mobile1 = "Nokia";
$mobile2 = "oppo";
$mobile3 = "samsung";
$mobile4 = "moto";

In PHP, there are three types of arrays:

  1. Indexed array - Array with a numeric index
  2. Associative array - Array with named keys
  3. Multidimensional array - Array containing one or more array

Indexed array

To create an array, we have a comma separated values in the array.

Syntax

array(var1,var2,var..n);

Example

<?php print_r(array("Nokia","oppo","samsung","moto")); ?>

Out Put

Array ( [0] => Nokia [1] => oppo [2] => samsung [3] => moto )

Associative array

Associative arrays, also called maps or dictionaries, are an abstract data type that can hold data in (key, value) pairs

Syntax

array('key1'=>'value1','key2'=>'value2',....n)

Example

<?php print_r(array('key1'=>'value1','key2'=>'value2')) ?>

Out Put

Array ( [key1] => value1 [key2] => value2 )

Multidimensional array

Multidimensional array is an array containing one or more arrays.

Syntax

array(
array('key1'=>'value1','key2'=>'value2'),
array('key3'=>'value3','key4'=>'value4'),
array('key5'=>'value5','key6'=>'value6')
)

Example

<?php print_r(array(
array('key1'=>'value1','key2'=>'value2'),
array('key3'=>'value3','key4'=>'value4'),
array('key5'=>'value5','key6'=>'value6')
)) ?>

Out Put

Array ( 
[0] => Array ( [key1] => value1 [key2] => value2 ) 
[1] => Array ( [key3] => value3 [key4] => value4 ) 
[2] => Array ( [key5] => value5 [key6] => value6 ) 
)

Stack Overlode is optimized Tutorials and examples for learning and training. Examples might be simplified to improve reading and learning and understand. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using Stack Overlode, you agree to have read and accepted our terms of use, cookie and privacy policy.