I have the following PHP code which uses foreach and gives the correct count. This is what I tried with loop.
$str = 'hello world';
$cnt = 0;
$arr = str_split($str);
foreach($arr as $val){
if( ord($val)%3 == 0 ){
$cnt++;
}
}
echo 'total count- '.$cnt; //count is 6 here which is correct
Is there a way of doing the same thing in PHP
without the use of loops or recursion?
You can use PHPs inbuilt array functions to do this, but internally they loop over the values themselves so is that valid? One way would be to use array_filter
on the results of str_split
and then getting the count of the number of values in the resultant array:
$str = 'hello world';
$cnt = count(array_filter(str_split($str), function ($v) { return ord($v) % 3 == 0; }));
echo $cnt;
Output
6
You can also do something similar with array_reduce
(this is most similar to your existing code):
$cnt = array_reduce(str_split($str), function ($c, $v) { return $c + (ord($v) % 3 == 0 ? 1 : 0); }, 0);