I have an array like
[0] Bert14:50
[1] hello
[2] Sarah14:50
[3] bye
[4] Dennis14:50
[5] hi
[6] wow
I want to reduce it to look like:
[0] Bert14:50
[1] Sarah14:50
[2] Dennis14:50
I've achieved that with this code:
//Doesn't any number exist in the array item? Then remove item
//by first setting it to NULL, and after the loop do some reindexing etc.
foreach($new_str as $item_key => &$item) {
if (!preg_match('~[0-9]+~', $item)) {
$item = null;
}
}
//Remove null by using unique array...
$new_str = array_values(array_unique($new_str));
//..and then remove first item if it's null
if ($new_str[0] === null) {unset($new_str[0]);}
But why does not this code do not remove items that does not contain 0-9? Why can't I unset a passed by reference value like this?
foreach($new_str as $item_key => &$item) {
if (!preg_match('~[0-9]+~', $item)) {
//Nothing seems to happen here. Output of $new_str is same as original
//array
unset($item);
}
}
array_filter().$new_str = preg_grep("~\d+~", $new_str);or more precise$new_str = preg_grep("~:\d+$~", $new_str);See 3v4l.org/YSkaI&$itemis a reference to the value in the array, not the value in the array (with it's own reference). Unsetting$itemremoves the iteration$itemvariable reference, not the value (and reference) in the array it points to. 3v4l.org/be7Qo