Constant arrays in PHP 7

PHPServer Side ProgrammingProgramming

In PHP 5.6, we could only initialize the constant arrays using the const keyword. For example,

conststudent_rollnos = [11,12,13,14,15];

In PHP 7, we can initialize constant arrays using the definefunction. For example,

define('subjects', ['Computer', 'operating system', 'networking', 'PHP 7','software engineering']);

Here, subjectsis the constant array name and the subjects constant array names are 'Computer', 'operating system', 'networking', 'PHP 7', and 'software engineering'.

Constant array index starts from 0, like any other array. Therefore, the computer elements will be at 0 indexes and the operating system will be at 1 index and, so on.

PHP 7 constant arrays Example

Live Demo

<?php
   const student_rollnos = [11,12,13,14,15];
   define('subjects', ['Computer', 'operating system', 'networking', 'PHP 7','software engineering']);
   print_r(student_rollnos);
   print_r(subjects);
?>

Output

The output for the above PHP 7 program will be −

Array
(
   [0] => 11
   [1] => 12
   [2] => 13
   [3] => 14
   [4] => 15
)
Array
(
   [0] => Computer
   [1] => operating system
   [2] => networking
   [3] => PHP 7
   [4] => software engineering
)

Explanation: In the above example, we used the define() function to declare an array name as subjects and 5 subjects name constants whose values cannot be changed.

raja
Published on 13-Mar-2021 11:45:24
Advertisements