29 of 110 menu

PHP Array Key

An array key in PHP is the unique name of an array element, which we can use to access that element.

If the array is not associative, PHP assigns keys automatically, starting from zero:

<?php $arr = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']; echo $arr[0]; // outputs 'Monday' ?>

We can assign keys ourselves:

<?php $arr = [1 => 'Monday', 2 => 'Tuesday', 3 => 'Wednesday', 4 => 'Thursday', 5 => 'Friday', 6 => 'Saturday', 7 => 'Sunday']; echo $arr[1]; // outputs 'Monday' ?>

It's not necessary to assign all keys - you can set one of them, and then PHP will continue the numbering automatically:

<?php $arr = [1 => 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']; echo $arr[2]; // outputs 'Tuesday' ?>

Keys don't necessarily have to be numbers, they can also be strings:

<?php $arr = ['Monday' => 1, 'Tuesday' => 2, 'Wednesday' => 3, 'Thursday' => 4, 'Friday' => 5, 'Saturday' => 6, 'Sunday' => 7]; echo $arr['Monday']; // outputs 1 ?>
English
БеларускаяEspañolРусский
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline