简体   繁体   中英

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

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?

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');
?>

try

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM