Filter array - odd even

后端 未结 7 2050
别那么骄傲
别那么骄傲 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:12

    I'd do it like this...

    for($i = 0; $i < count($array); $i++)
    {
        if($i % 2) // OR if(!($i % 2))
        {
            unset($array[$i]);
        }
    }
    
    0 讨论(0)
  • 2021-01-12 06:17
    <?php 
    $array = array(0, 3, 5, 7, 20, 10, 99,21, 14, 23, 46); 
    for ($i = 0; $i < count($array); $i++) 
    
    { 
            if ($array[$i]%2 !=0)
            echo $array[$i]."<br>";
    }
    ?> 
    
    0 讨论(0)
  • 2021-01-12 06:25

    Here's a "hax" solution:

    Use array_filter in combination with an "isodd" function.

    array_filter seems only to work on values, so you can first array_flip and then use array_filter.

    array_flip(array_filter(array_flip($data), create_function('$a','return $a%2;')))
    
    0 讨论(0)
  • 2021-01-12 06:30

    foreach($arr as $key => $value) if($key&1) unset($arr[$key]);

    The above removes odd number positions from the array, to remove even number positions, use the following:

    Instead if($key&1) you can use if(!($key&1))

    0 讨论(0)
  • 2021-01-12 06:32

    You could also use SPL FilterIterator like this:

    class IndexFilter extends FilterIterator {
        public function __construct (array $data) {
            parent::__construct(new ArrayIterator($data));
        }   
    
        public function accept () {
            # return even keys only
            return !($this->key() % 2);
        }     
    }
    
    $arr      = array('string1', 'string2', 'string3', 'string4');
    $filtered = array();
    
    foreach (new IndexFilter($arr) as $key => $value) {
        $filtered[$key] = $value;
    }
    
    print_r($filtered);
    
    0 讨论(0)
  • 2021-01-12 06:32
    <?php
    function odd($var)
    {
        // returns whether the input integer is odd
        return($var & 1);
    }
    
    function even($var)
    {
        // returns whether the input integer is even
        return(!($var & 1));
    }
    
    $array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
    $array2 = array(6, 7, 8, 9, 10, 11, 12);
    
    echo "Odd :\n";
    print_r(array_filter($array1, "odd"));
    echo "Even:\n";
    print_r(array_filter($array2, "even"));
    ?>
    
    Odd :
    Array
    (
        [a] => 1
        [c] => 3
        [e] => 5
    )
    Even:
    Array
    (
        [0] => 6
        [2] => 8
        [4] => 10
        [6] => 12
    )
    
    0 讨论(0)
提交回复
热议问题