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 −

constARR=array(val1, val2, val3);

Example

Open Compiler

<?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 −

constFRUITS=["Watermelon","Strawberries","Pomegranate","Blackberry",];
Ezoic

Example

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

Open Compiler

<?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

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

Constant Arrays PHP 7 Onwards

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

Open Compiler

<?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 −

Open Compiler

<?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
)

Comments

Leave a Reply

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