TransWikia.com

Deleting from array using unset creates values

Stack Overflow Asked by Cameron on January 11, 2021

$array = [ 0, 5, 7 ];

For this array, I want to unset without it assigning a value.

When I unset($array[5]) it will return

{
    "0" => 0,
    "1" => 5,
    "2" => 7
}

But my actual goal is to make it return like

[ 0, 7 ]

That way when I use json_encode it will just show up as

[ 
    0,
    7
]

Is this possible at all? I googled and everyone just mentions indexing, but I am looking at just removing this number from the array. Not have it reindex or change the formatting of it to have a value.

2 Answers

$a = [0,5,7];
array_splice($a, 1, 1); // remove from position 1 - remove 1 entry

echo json_encode($a);

Working example.

output

[0,7]

references

additional informaion

Unset wont work as is, since it preserves the initial keys.

A solution with unset is to ignore the keys by using array_values:

$a = [0,5,7];

unset($a[1]);
$a = array_values($a);

echo json_encode($a);

Working example.

Same output as above.

Answered by SirPilan on January 11, 2021

The parameter within the brackets on $array[] is actually the numerical index or associative index (arrays in PHP are maps).

In your case, you want to do:

unset($arr[1]);

Answered by maio290 on January 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP