douyi0219 2010-02-24 01:14
浏览 18
已采纳

键入检查所有数组元素

Is there any simple way of checking if all elements of an array are instances of a specific type without looping all elements? Or at least an easy way to get all elements of type X from an array.

  • 写回答

4条回答 默认 最新

  • doujun5009 2010-02-24 01:19
    关注

    You cannot achieve this without checking all the array elements, but you can use built-in array functions to help you.

    You can use array_filter to return an array. You need to supply your own callback function as the second argument to check for a specific type. This will check if the numbers of the array are even.

    function even($var){
      return(!($var & 1));
    }
    
    // assuming $yourArr is an array containing integers.
    $newArray = array_filter($yourArr, "even");
    // will return an array with only even integers.
    

    As per VolkerK's comment, as of PHP 5.3+ you can also pass in an anonymous function as your second argument. This is the equivalent as to the example above.

    $newArray = array_filter($yourArr, function($x) { return 0===$x%2; } );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?