PHP - Array Accessing arrays

Introduction

Lists are treated internally as a map with numeric keys in order.

The first key is always 0; so, an array with n elements will have keys from 0 to n-1.

You can add any key to a given array, even if it previously consisted of numeric entries.

The problem arises when adding numeric keys, and later, you try to append an element to the array.

What do you think will happen?

Demo

<?php
     $names = ['A', 'B', 'C']; 
     $names['z'] = 'Z'; 
     $names[8] = 'S'; 
     $names[] = 'M'; 
     print_r($names); /* www  . ja v a 2  s .  co  m*/
?>

Result

When trying to append a value, PHP inserts it after the last numeric key, in this case 8.

Demo

<?php
    $names = ['A', 'B', 'C']; 
    print_r($names[1]); // prints 'B' 
?>//w  w w  .  j a  v  a 2s.  com

Result

Finally, trying to access a key that does not exist in an array will return you a null and throw a notice.

Demo

<?php
    $names = ['A', 'B', 'C']; 
    var_dump($names[4]); // null and a PHP notice 
?>//from   w ww . ja  v a 2 s  .c  o  m

Result

Related Topic