You can easily remove any elements from a given array inside your PHP code using the function unset(); You just need the array name with index to remove it. I'm giving a small example, which will help to understand about removing any element from your PHP array.
The given example will declare an array of 10 elements from 1 to 10. It will print 10 elements using comma separation. After that it will remove 2 elements from the array, and print the elements again. And you'll find that 2 elements are missing after delete from first array set.
## your initial PHP array
$array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
## output your array
print implode(' ,', $array) . "\n";
## Output : 1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10
## removing 2 values from array
unset($array[5]);
unset($array[7]);
print implode(' ,', $array) . "\n";
## Output : 1 ,2 ,3 ,4 ,5 ,7 ,9 ,10
The given example will declare an array of 10 elements from 1 to 10. It will print 10 elements using comma separation. After that it will remove 2 elements from the array, and print the elements again. And you'll find that 2 elements are missing after delete from first array set.
Comments
$arr = array(1, 2, 3, 4);
var_dump($arr);
// [0] => 1; [1] => 2; [2] => 3; [3] => 4;
unset($arr[2]);
var_dump($arr);
// [0] => 1; [1] => 2; [3] => 4;
the index will not change if an element has been removed.
I don't think this a really remove.
If the element is gone, it's removed.
That's not a bug.
it is by
$myar = array_values($myar);
it is by
$myar = array_values($myar);
it is by
$myar = array_values($myar);
The effect you want can be achieved by using array_splice() which removes the item and re-indexes the array.
Great post! Yes, unset just leaves the indices as they were before, and does not rearrange them. There are some alternatives and workarounds as clearly explained here:
Delete an element from an array in PHP