On JS for this there is a function some() , is there an analogue of such a function in PHP?

I did not find this in the list of functions for working with arrays.

I need to check if there is at least one element in the array that is not an empty string. I tried in_array(!'', $arr) , but this function in_array(!'', $arr) not work correctly if the array element is '0' . Another idea is to do this: implode($arr) != '' , But in my opinion this is not the best solution.

  • php.su/in_array - Urmuz Tagizade
  • @vitidev and the closest, but it will not stop and return the array, not the boolean value - splash58
  • function some($array, $function) { return count(array_filter($array,$function)) != 0; } function some($array, $function) { return count(array_filter($array,$function)) != 0; } - splash58
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

5 answers 5

You can write such a function yourself, for example, as follows.

 <?php function some($arr) { foreach($arr as $value) { if($value !== '') return true; } return false; } $arr = ['', 0, '', '']; echo some($arr); 

As I understand from the comments, it is important for you to distinguish empty lines and the value 0 In this case, when comparing, it is better to use the equivalence operators === and nonequivalence !== , which, in addition to the value, also check the type of variables.

The above variant is sharpened only for one specific case, however, if you pass some() functions as an argument to the callback function, you can make it more universal by changing the decision conditions on the fly using an anonymous function

 <?php function some($arr, $callback) { foreach($arr as $value) { if($callback($value)) return true; } return false; } $arr = ['', 0, '', '']; echo some($arr, function($value){ return $value !== ''; }); 

    If you simply determine if there is a value then you can:

     $a = [ "a","b","c","d","1","2" ]; echo (in_array("a" , $a) ? true : false); //true echo (in_array("aa" , $a) ? true : false);//false echo (array_search("c" , $a) ? true : false);//true echo (array_search("cc" , $a) ? true : false);//false echo (array_flip($a)['d'] ? true : false);//true echo (array_flip($a)['dd'] ? true : false);//false 

      array_filter will not return empty strings. Therefore, it is possible to check that all lines are not empty.

       count(array_filter($array)) != 0; 
      • array_filter strings of zeros will also be eliminated - user208916
      • Write custom kolbek with strict verification. - u_mulder

      Maybe you need it? array_map() . Applies a callback function to all elements of the specified arrays.

        join($arr) != 0; You can try this, but this is similar to implode() course, you can also write some () function, but I think you should not