PHP - Array Update arrays

Introduction

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.

Treating it as a list means appending another element to the end of the array:

Demo

<?php
    $names = ['A', 'B', 'C']; 
    $status = [ //from www  .j a v a  2  s  .  co m
        'name' => 'A', 
        'status' => 'dead' 
    ]; 
    $names[] = 'V'; 
    $status['age'] = 32; 
    print_r($names, $status); 
?>

Result

Here, the part appends the name V to the list of names, hence the list will look like ['A', 'B', 'C', 'V'].

The second change adds a new key-value to the array.

You can check the result from your browser by using the function print_r.

If you need to remove an element from the array, instead of adding or updating one, you can use the unset function:

Demo

<?php
    $status = [ //  w  w w  .  ja v a  2  s .co m
        'name' => 'A', 
        'status' => 'dead' 
    ]; 
    unset($status['status']); 
    print_r ($status); 
?>

Result

The new $status array contains the key name only.

Related Topic