Google News
logo
PHP Program to Create a Array constant with define()
In PHP, you can define an array constant using the `define()` function. Here's an example :
Program :
<?php
define('FRUITS', ['apple', 'banana', 'orange']);
echo FRUITS[1];  // outputs "banana"
?>
Output :
banana
In this example, an array constant named `FRUITS` is defined using the `define()` function. The value of the constant is an array containing the strings `"apple"`, `"banana"`, and `"orange"`.

The `echo` statement outputs the value of the element at index 1 of the `FRUITS` array, which is `"banana"`.

Note that array constants can only be defined using the `define()` function in PHP 7.0 and later. In earlier versions of PHP, you would need to use the `const` keyword to define a scalar constant, and the `define()` function with an array variable to define an array constant.

Here's an example using earlier versions of PHP :
Program :
<?php
const FRUITS = ['apple', 'banana', 'orange'];
define('VEGGIES', ['carrot', 'celery', 'broccoli']);

echo FRUITS[0];     
echo VEGGIES[2]; 
?>
Output :
apple
broccoli
In this example, a scalar constant named `FRUITS` is defined using the `const` keyword. An array constant named `VEGGIES` is defined using the `define()` function with an array variable.

The `echo` statements output the values of the elements at index 0 of the `FRUITS` array and index 2 of the `VEGGIES` array.