Arrays are not immutable, that is, they can change after being initialized. You can change the content of an array either by treating it as a map or as a list. Treating it as a map means that you specify the key that you want to override, whereas treating it as a list means appending another element to the end of the array:
<?php $names = ['Harry', 'Ron', 'Hermione']; $status = [ 'name' => 'James Potter', 'status' => 'dead' ]; $names[] = 'Neville'; $status['age'] = 32; print_r($names, $status);
In the preceding example, the first highlighted
line appends the name Neville
to the
list of names, hence the list will look like ['Harry', 'Ron', 'Hermione',
'Neville']. The second change actually adds a new
key-value to the array. You can check the result from your browser
by using the function print_r
. It does
something similar to var_dump
, just
without the type and size of each value.
Note
print_r and var_dump in a browser
When printing the content of an array, it is useful to see one key-value per line, but if you check your browser, you will see that it displays the whole array in one line. That happens because what the browser tries to display is HTML, and it ignores new lines or whitespaces. To check the content of the array as PHP wants you to see it, check the source code of the page—you will see the option by right-clicking on the page.
If you need to remove an element from the
array, instead of adding or updating one, you can use the
unset
function:
<?php
$status = [
'name' => 'James Potter',
'status' => 'dead'
];
unset($status['status']);
print_r ($status);