Filter array - odd even

后端 未结 7 2059
别那么骄傲
别那么骄傲 2021-01-12 05:56

How can a filter out the array entries with an odd or even index number?

Array
(
    [0] => string1
    [1] => string2
    [2] => string3
    [3] =&         


        
相关标签:
7条回答
  • 2021-01-12 06:32
    $array = array(0 => 'string1', 1 => 'string2', 2 => 'string3', 3 => 'string4');
    
    // Removes elements of even-numbered keys
    $test1 = array_filter($array, function($key) {
        return ($key & 1);
    }, ARRAY_FILTER_USE_KEY);
    
    // Removes elements of odd-numbered-keys
    $test2 = array_filter($array, function($key) {
        return !($key & 1);
    }, ARRAY_FILTER_USE_KEY);
    

    This answer is a bit of an improvement over this answer. You can use anonymous functions instead of create_function. Also, array_filter takes an optional flag parameter that lets you specify that the callback function takes the key as its only argument. So you don't need to use array_flip to get an array of keys.

    0 讨论(0)
提交回复
热议问题