PHP Arrays

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

An array is a data structure that stores an arbitrary number of values in a single value. An array in PHP is actually an ordered map, where map is a type that associates values to keys.

Syntax

  • $array = array('Value1', 'Value2', 'Value3'); // Keys default to 0, 1, 2, ...,
  • $array = array('Value1', 'Value2', ); // Optional trailing comma
  • $array = array('key1' => 'Value1', 'key2' => 'Value2', ); // Explicit keys
  • $array = array('key1' => 'Value1', 'Value2', ); // Array ( ['key1'] => Value1 [1] => 'Value2')
  • $array = ['key1' => 'Value1', 'key2' => 'Value2', ]; // PHP 5.4+ shorthand
  • $array[] = 'ValueX'; // Append 'ValueX' to the end of the array
  • $array['keyX'] = 'ValueX'; // Assign 'valueX' to key 'keyX'
  • $array += ['keyX' => 'valueX', 'keyY' => 'valueY']; // Adding/Overwrite elements on an existing array

Parameters

ParameterDetail
KeyThe key is the unique identifier and index of an array. It may be a string or an integer. Therefore, valid keys would be 'foo', '5', 10, 'a2b', ...
ValueFor each key there is a corresponding value (null otherwise and a notice is emitted upon access). The value has no restrictions on the input type.

Remarks



Got any PHP Question?