PHP – Constant Arrays


PHP – Constant Arrays



”;


It was not possible to declare a constant array before PHP version 5.6. From PHP 5.6 onwards, you can use the “const” keyword to declare a constant array. From PHP 7 onwards, constant arrays can also be formed with define() function.

A constant array is an array which cannot be modified after it has been formed. Unlike a normal array, its identifier doesn’t start with the “$” sign.

The older syntax for declaring constant array is −


const ARR = array(val1, val2, val3);

Example


<?php
   const FRUITS = array(
      "Watermelon", 
      "Strawberries",
      "Pomegranate",
      "Blackberry",
   );
   var_dump(FRUITS);
?>

It will produce the following output


array(4) {
   [0]=>
   string(10) "Watermelon"
   [1]=>
   string(12) "Strawberries"
   [2]=>
   string(11) "Pomegranate"
   [3]=>
   string(10) "Blackberry"
}

You can also use the conventional square bracket syntax to declar a constant array in PHP −


const FRUITS = [
   "Watermelon", 
   "Strawberries",
   "Pomegranate",
   "Blackberry",
];

Example

It is not possible to modify any element in a constant array. Hence, the following code throws a fatal error −


<?php
   const FRUITS = [
      "Watermelon", 
      "Strawberries",
      "Pomegranate",
      "Blackberry",
   ];
   FRUITS[1] = "Mango";
?>

It will produce the following output


PHP Fatal error:  Cannot use temporary expression in write context

Constant Arrays PHP 7 Onwards

The newer versions of PHP allow you to declare a constant array with define() function.


<?php
   define (''FRUITS'',  [
      "Watermelon", 
      "Strawberries",
      "Pomegranate",
      "Blackberry",
   ]);
   print_r(FRUITS);
?>

It will produce the following output


Array
(
   [0] => Watermelon
   [1] => Strawberries
   [2] => Pomegranate
   [3] => Blackberry
)

You can also use the array() function to declare the constant array here.


define (''FRUITS'',  array(
   "Watermelon", 
   "Strawberries",
   "Pomegranate",
   "Blackberry",
));

Example

It is also possible to declare an associative constant array. Here is an example −


<?php
   define (''CAPITALS'',  array(
      "Maharashtra" => "Mumbai",
      "Telangana" => "Hyderabad",
      "Gujarat" => "Gandhinagar",
      "Bihar" => "Patna"
   ));
   print_r(CAPITALS);
?>

It will produce the following output


Array
(
   [Maharashtra] => Mumbai
   [Telangana] => Hyderabad
   [Gujarat] => Gandhinagar
   [Bihar] => Patna
)

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *