Home‎ > ‎PHP‎ > ‎

Arrays

PHP have three style of Arrays
  • Numerical Arrays or Single Dimensional
  • Associative Arrays or Key Value Pairs
  • Multidimensional Arrays
PHP array can contain both Integer and String values together.

Syntax - array() ;

Single Dimensional

$arr = array("one" , 2) ;

// Display array values using index.
echo $arr[0] ; // Display one
echo $arr[1] ; // Display 2

Destory the array - using unset() function and also use for unset the value of variable

Example:
unset($arr) ; // delete an array
unset($arr[0]) ; // delete element in array

Access using loops.

for-loops

count(array) - return the length of an array

for($i = 0; $i < count($arr); $i++)
{
    echo $arr[$i] ."<br>"; // echo the content with concat with HTML <br> tag that breaks the lines.
}

or

foreach($arr as $val)
{
    echo $val ; // here $arr iterate and store the value in $val
}

or test the content in array

PHP Provide print_r(array) function - return the array in human readable form with all index and values. display like JSON format

Example : use HTML pre tag that format text and, also work well without pre tag
echo "<pre>" ;
    print_r($arr) ;
echo "</pre>" ;

Output:
Array
(
[0] => one
[1] => 2
)

or

PHP Provide var_dump() function that represent structure information of array including datatype and length of each variable.

Example :
echo "<pre>" ;
    var_dump($arr) ;
echo "</pre>" ;

Output :
array(2) {
[0]=>
string(3) "one"
[1]=>
int(2)
}

where,
  • array(2) - denote the size of an array.
  • string(3) - denote the length and datatype
  • int(2) - denote the length and datatype assign to variable
PHP Provide Array representation in JSON Format using json_encode($value)

Example :
echo json_encode($arr) ;

Output :
["one",2]
and similar also provide json_decode($json) function that convert JSON format in PHP arrays.


Key Value Pairs



Multidimensional Array



Complete array function in PHP
Comments