I have done a lot of researching, and I cant find out how to delete an element from an array in PHP. In Java, if you have an ArrayList<SomeObject> list
, you would say list.remove(someObject);
.
Is there anything similar you can do in PHP? I have found unset($array[$index]);
, but it doesnt seem to work.
Thanks for your help in advance!
4 Answers 4
unset
should work, you can also try this:
$array = array_merge(
array_slice($array, 0, $index),
array_slice($array, $index+1)
);
1 Comment
You need to either remove it and remove the empty array:
function remove_empty($ar){
$aar = array();
while(list($key, $val) = each($ar)){
if (is_array($val)){
$val = remove_empty($val);
if (count($val)!=0){
$aar[$key] = $val;
}
}
else {
if (trim($val) != ""){
$aar[$key] = $val;
}
}
}
unset($ar);
return $aar;
}
remove_empty(array(1,2,3, '', 5)) returns array(1,2,3,5)
1 Comment
unset($array[$index]);
actually works.
The only issue I can think of is the way you're iterating this array.
just use foreach
instead of for
also make sure that $index contains correct value
to test your array you can use var_dump()
:
$cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";
unset($cars[0]);
var_dump($cars);
1 Comment
If you want to delete just one array element you can use unset()
or alternative array_splice()
Unset()
Example :
Code
<?php
$array = array(0 => "x", 1 => "y", 2 => "z");
unset($array[1]);
//If you want to delete the second index ie, array[1]
?>
Output
Array (
[0] => a
[2] => c
)
doesnt seem to work
unset
is correct. How have you determined that it doesn't work?