PHP: Arrays

PHP is a popular server-side scripting language mostly used for web-development. PHP does not need to be embedded in HTML tags. PHP code will be in <?php and ?> delimiters (short form <? and ?>).

PHP Arrays are ordered maps contains key, value pairs. Keys can be either integers or strings. String keys are case-sensitive (e.g.: “flowers” and “Flowers” are different keys). Values can be of any type that PHP can handle; even can be arrays, complex structures and multidimensional arrays.

PHP Arrays can be created by using array() or [].

<?php
   $fruits = array("A" => "Apple", "B" => "Banana", "M" => "Mango");

   // -- This is also valid
   // $fruits = ["A" => "Apple", "B" => "Banana", "M" => "Mango"];

   print_r($fruits);
?>

Output will be like this:

Array ( [A] => Apple [B] => Banana [M] => Mango )

The key is optional in PHP Arrays. If the key is not specified for all elements, PHP will start indexing from 0. If the key is not specified for some elements, PHP will use the increment of the largest previously used integer key for those elements. Note that previously used integer may not currently exists in the array. That means, the integer key might have used earlier and deleted.

<?php
  $flowers = array("Lily", "Orchid", "Rose", 10 => "Tulip", "Sunflower", "Tansy");

  print_r($flowers);
?>

Observe that in the above example, array elements are specified without keys. The key will start from 0. In the middle of the array, specified an integer key 10. Then the next key will start from 11 and so on. See below the output of above example for clear understanding:

Array ( [0] => Lily [1] => Orchid [2] => Rose [10] => Tulip [11] => Sunflower [12] => Tansy )

PHP Array values can be accessed using [] (square brackets) or {} (curly braces).

print $fruits["A"];
// -- This is also valid
// print $fruits{"A"};

Above statement will result “Apple”.

Usually in other programming languages like C, C++; Arrays hold same type of elements. But PHP Arrays can hold mixed value types. That means, integers, strings, arrays and etc.,. For eg:

<?php
   $mixed = array(1 => 1000, "A" => "Apple", "Flowers" => $flowers);

   print_r($mixed);
   // -- To display "Rose" from $flowers
   print_r($mixed["Flowers"][2]);
?>

To remove elements from an Array, PHP provides unset function. See below example; this will remove an element with key “1” from $flowers PHP Array.

<?php
  unset($flowers[1]);
  print_r($flowers);
?>

There are lot of useful functions on PHP Arrays, like sort to sort array elements, count to return count of elements, etc.,.

– PHP: Arrays

Leave a Reply