4 ms·
php > $array = [1,2,3,4]; php > var_dump(array_filter($array, function($x) { return $x %2 === 0; })); php shell code:1: array(2) { [1] => int(2) [3] =>
by thinkindie 6y ago
php > $array = [1,2,3,4];
php > var_dump(array_filter($array, function($x) { return $x %2 === 0; }));
php shell code:1:
array(2) {
[1] =>
int(2)
[3] =>
int(4)
}
what's the problem with array_filter then? That keys are not reindexed?
- arnvald 6y agoYeah, an array essentially becomes an associative array. For example in another language I could do something like: if (!empty($filteredArray)) { print($filteredArray[0] } But in PHP I need to remember that after every array_filter, after every unset etc. I need to reindex the array, because [0] element might not be there
- greenshackle2 6y agoIt was an associative array all along, PHP just hides that from you. The Array is such a quirky data structure, it takes int or string keys, but numeric string keys ("1", etc.) are silently converted to int. It's never a real array, the implementation under the hood is a hash table.