Say I have an array:
$before = array(1,2,3,3,4,4,4,5)
How would I remove just one occurence of eg '3' ?
$after = array(1,2,3,4,4,4,5)
(I don't know where in the array that number will be)
Say I have an array:
$before = array(1,2,3,3,4,4,4,5)
How would I remove just one occurence of eg '3' ?
$after = array(1,2,3,4,4,4,5)
(I don't know where in the array that number will be)
You can use a variety of methods, depending on what exactly you're trying to do:
array_search() and then unset() it.array_splice() to replace it with nothing.array_filter() with a custom callback.Generic routine, just populate the $reduceValues array with the values you want reducing to singletons.
$before = array(1,2,2,2,3,3,4,4,4,5,5);
$reduceValues = array(3,5);
$toReduce = array_fill_keys($reduceValues,TRUE);
$after = array_filter( $before,
function($data) use ($reduceValues,&$toReduce) {
if (in_array($data,$reduceValues)) {
if ($toReduce[$data]) {
$toReduce[$data] = FALSE;
return TRUE;
}
return FALSE;
}
return TRUE;
}
);
var_dump($after);
There are several ways to do what you ask. Which one you should use depends on the context of its usage, as well as the exact result you desire. I prefer array_splice(), because it maintains the array numbering. If you want the easiest method, I suggest unset(). If you are looking for a way to eliminate the dupes, use array_unique(). With the latter two, if you need to renumber them back the way they were, use array_values(). If you do not know the index of the value you need to remove, you can use one of the above in conjunction with array_search(). If you need a more advanced filter, use array_filter().
<?php
header('Content-Type: text/plain');
$original = array(1,2,3,3,4,4,4,5);
echo "ORIGINAL:\n";
print_r($original);
echo "\n\n";
echo "Using array_splice():\n";
$new = $original;
array_splice($new, 3, 1);
print_r($new);
echo "\n\n";
echo "Using array_unique() to remove dupes:\n";
$new = array_unique($original);
$new = array_values($new);
print_r($new);
echo "\n\n";
echo "Using unset:\n";
$new = $original;
unset($new[3]);
$new = array_values($new);
print_r($new);
echo "\n\n";
echo "Using array_search & unset:\n";
$new = $original;
unset($new[array_search('3', $new)]);
$new = array_values($new);
print_r($new);
echo "\n\n";
?>