PHP - Array Arrays

Introduction

PHP An array is a data structure that implements list and map.

Initializing arrays

You have different options for initializing an array.

You can initialize an empty array, or you can initialize an array with data.

There are different ways of writing the same data with arrays too.

Demo

<?php
     $empty1 = []; /*from  w w  w .ja v a  2  s. c om*/
     $empty2 = array(); 
     $names1 = ['A', 'B', 'C']; 
     $names2 = array('A', 'b', 'c'); 
     $status1 = [ 
        'name' => 'a', 
        'status' => 'dead' 
     ]; 
     $status2 = array( 
        'name' => 'a', 
        'status' => 'dead' 
     ); 
?>

Here, we define the list and map.

$names1 and $names2 are exactly the same array, just using a different notation.

The same happens with $status1 and $status2.

Finally, $empty1 and $empty2 are two ways of creating an empty array.

Internally, the array $names1 is a map, and its keys are ordered numbers.

In this case, another initialization for $names1 that leads to the same array could be as follows:

$names1 = [ 
   0 => 'A', 
   1 => 'B', 
   2 => 'C' 
]; 

Keys of an array can be any alphanumeric value, like strings or numbers.

Values of an array can be anything: strings, numbers, Booleans, other arrays, and so on.

You could have something like the following:

$books = [ 
    '2018' => [ 
        'author' => 'G', 
        'finished' => true, 
        'rate' => 9.5 
    ], 
    'Java' => [ 
        'author' => 'W', 
        'finished' => false 
    ] 
]; 

This array is a list that contains two arrays-maps.

Each map contains different values like strings, doubles, and Booleans.

Related Topics