Home > Blockchain >  PHP count values in multidimensional-array where key and value equals
PHP count values in multidimensional-array where key and value equals

Time:12-24

I'm trying to create a dashboard with some information like how many users are male or female. I'm storing profile information already in one multidimensional-array called 'users'. To count the total male/female users I want to use a function with multiple arguments (the array, key and value.

I tried the following code:

  <?
    function countArray($array, $key, $value) {
      $cnt = count(array_filter($array,function($element) {
        return $element[$key]== $value;
      }));
      echo $cnt;
    }

    countArray($users, 'gender', '1');
  ?>

This results in Undefined variable: key/values. What am I doing wrong?

CodePudding user response:

The problem is that anonymous functions in PHP do not have access to variables outside of their own scope. As such, the array_filter() callback function you've provided has no knowledge of $key or $value, and so they're undefined variables within that function scope. To fix this, you must explicitly pass the external variables into the function scope using the use keyword, like function() use ($external_variable) {}.

In your case, the solution would look something like this:

<?
    function countArray($array, $key, $value) {
      $cnt = count(array_filter($array,function($element) use ($key, $value) {
        return $element[$key]== $value;
      }));
      echo $cnt;
    }

    countArray($users, 'gender', '1');
?>

If you're using PHP 7.4 or above, you can also just use an arrow function to allow the external scope to become part of the function scope implicitly:

<?
    function countArray($array, $key, $value) {
      $cnt = count(array_filter($array,fn($element) => $element[$key]== $value ));
      echo $cnt;
    }

    countArray($users, 'gender', '1');
?>

CodePudding user response:

try

function($element) use ($key, $value) {
  • Related