Wednesday, February 20, 2019

How to remove value and reassign remaining values to keys in array in PHP





The below code,



$test_array = array("a","b","c","d","e");
echo "
";
htmlspecialchars(print_r($test_array));

echo "
";


which gives output like,



Array
(
[0] => a
[1] => b
[2] => c

[3] => d
[4] => e
)


I want to remove a specific entry say from index 2 and re-index the array as below,



Array
(
[0] => a

[1] => b
[2] => d
[3] => e
)


How to do that?


Answer



Use array_splice




array_splice($test_array, 2, 1);


The second argument is your index that you want to nix and the third is how many elements you want gone.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...