Trong PHP 5.6, chỉ có thể khởi tạo mảng hằng số dùng từ khóa const. Ví dụ:
const student_rollnos = [11,12,13,14,15];
Trong PHP 7, có thể khởi tạo mảng hằng số dùng hàm define(). Ví dụ:
define('subjects', ['Computer', 'operating system', 'networking', 'PHP 7', 'software engineering']);
Ở đây, subjects là tên mảng hằng số và các tên hằng số trong mảng subjects là 'Computer', 'operating system', 'networking', 'PHP 7', 'software engineering'.
Chỉ số mảng hằng số bắt đầu từ 0 như mảng thường. Do đó phần tử Computer ở chỉ số 0, operating system ở 1, v.v.
Ví dụ mảng hằng số PHP 7
<?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);
?>
Kết quả
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
)
Giải thích: Trong ví dụ trên, dùng hàm define() khai báo mảng tên subjects và 5 hằng số môn học giá trị không thể thay đổi.