After array_filter(), how can I reset the keys to go in numerical order starting at 0

旧巷老猫 提交于 2019-11-26 15:36:40

问题


I just used array_filter to remove entries that had only the value '' from an array, and now I want to apply certain transformations on it depending on the placeholder starting from 0, but unfortunately it still retains the original index. I looked for a while and couldn't see anything, perhaps I just missed the obvious, but my question is...

How can I easily reset the indexes of the array to begin at 0 and go in order in the NEW array, rather than have it retain old indexes?


回答1:


If you call array_values on your array, it will be reindexed from zero.




回答2:


If you are using Array filter do it as follows

$NewArray = array_values(array_filter($OldArray));



回答3:


Use array_values():

<?php

$array = array('foo', 'bar', 'baz');
$array = array_filter($array, function ($var) {
    return $var !== 'bar';
});

print_r($array); // indexes 0 and 2
print_r(array_values($array)); // indexes 0 and 1



回答4:


I worry about how many programmers have innocently copy/pasted the array_values(array_filter()) method into their codes -- I wonder how many programmers unwittingly ran into problems because of array_filter's greed. Or worse, how many people never discovered that the function purges too many values from the array...

I will present a better alternative for the two-part process of stripping NULL elements from an array and re-indexing the keys.

However, first, it is extremely important that I stress the greedy nature of array_filter() and how this can silently monkeywrench your project. Here is an array with mixed values in it that will expose the trouble:

$array=['foo',NULL,'bar',0,false,null,'0',''];

Null values will be removed regardless of uppercase/lowercase.

But look at what remains in the array when we use array_values() & array_filter():

array_values(array_filter($array));

Output array ($array):

array (
  0 => 'foo',
  1 => 'bar'
)
// All empty, zero-ish, falsey values were removed too!!!

Now look at what you get with my method that uses array_walk() & is_null() to generate a new filtered array:

array_walk($array,function($v)use(&$filtered){if(!is_null($v)){$filtered[]=$v;}});

This can be written over multiple lines for easier reading/explaining:

array_walk(                      // iterate each element of an input array
    $array,                      // this is the input array
    function($v)use(&$filtered){ // $v is each value, $filter (output) is declared/modifiable
        if(!is_null($v)){        // this literally checks for null values
            $filtered[]=$v;      // value is pushed into output with new indexes
        }
    }
);

Output array ($filter):

array (
  0 => 'foo',
  1 => 'bar',
  2 => 0,
  3 => false,
  4 => '0',
  5 => '',
)

With my method you get your re-indexed keys, all of the non-null values, and none of the null values. A clean, portable, reliable one-liner for all of your array null-filtering needs. Here is a demonstration.



Similarly, if you want to remove empty, false, and null elements (retaining zeros), these four methods will work:

var_export(array_values(array_diff($array,[''])));

or

var_export(array_values(array_diff($array,[null])));

or

var_export(array_values(array_diff($array,[false])));

or

var_export(array_values(array_filter($array,'strlen')));

Output:

array (
  0 => 'foo',
  1 => 'bar',
  2 => 0,
  3 => '0',
)

Finally, for anyone who prefers the syntax of language constructs, you can also just push qualifying values into a new array to issue new indexes.

$array=['foo', NULL, 'bar', 0, false, null, '0', ''];

$result = [];
foreach ($array as $value) {
    if (strlen($value)) {
        $result[] = $value;
    }
}

var_export($result);


来源:https://stackoverflow.com/questions/3401850/after-array-filter-how-can-i-reset-the-keys-to-go-in-numerical-order-starting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!