php - Count specific array values with same part -
i found lot of samples how count positions or occurrences in arrays actualy doesnt solve problem.
my array looks like:
$foo = array( "foo"=>"bar", "bar"=>"foo", "hello"=>"world", "world"=>"hello", "grt1"=>"a", "grt2"=>"b", "grt3"=>"c", "grt4"=>"d", "grt5"=>"e", "gr1"=>2, "gr2"=>0, "gr3"=>, "gr4"=>5, "gr5"=> )
what want achive count how many gr{i}
in array.
the thing is, dont want count grt{i}
. result sample should 5.
array_count_values
not me in case.
my try atm is:
$count = 0; for($i=0;$i<count($foo);$i++){ if(array_key_exists("gr".$i, $foo)){ $count++ } }
is way ? or there nicer way ?
edit: since need result loop (for) rid of loop.
array_reduce() job
$count = array_reduce(array_keys($foo), function($c, $k){ return preg_match('/^gr\d+$/', $k) ? ++$c : $c; }, 0);
Comments
Post a Comment