Main
Main

Reputation: 21

Unable to count number of occurrence of a word in an array PHP

I am trying to create a program that counts the number of occurrence of a word in the array. When I tried to run my program by putting in the actual string word in the return statement it worked. As can be seen below:

<!DOCTYPE html>
<html>
<body>

<?php
$a=array();
array_push($a,"blue","blue","yellow");
print_r($a);
$cnt = count(array_filter($a,function($a) {return $a=="blue";}));
print($cnt);
if (in_array("blue", $a)) 
  { 
  echo "found"; 
  } 
?>

</body>
</html>

However, this is not how I want to design my program, I want to store the word in a string and use that in the return statement but when I try to do that it doesn't work. Here is the code that isn't working:

<!DOCTYPE html>
<html>
<body>

<?php
$a=array();
array_push($a,"blue","blue","yellow");
print_r($a);
$check="blue";
$cnt = count(array_filter($a,function($a) {return $a==check;}));
print($cnt);
if (in_array("blue", $a)) 
  { 
  echo "found"; 
  } 
?>

</body>
</html>

The output shows 0 for $cnt..

Upvotes: 0

Views: 28

Answers (1)

Phil
Phil

Reputation: 164731

Your script will be throwing an undefined constant error because check is not defined. Nor is the variable $check in the scope of the array_filter() anonymous function.

You can pass in scope via the use statement

$cnt = count(array_filter($a, function($a) use ($check) {
    return $a == $check;
}));

See Inheriting variables from the parent scope


If you're after counts though, why not use array_count_values()

$a = ["blue", "blue", "yellow"];
$counts = array_count_values($a);

$blueCount = $counts["blue"] ?? 0;
if ($blueCount > 0) {
    echo "Found 'blue' $blueCount times";
}

Upvotes: 3

Related Questions