Home > Back-end >  PHP Associative Array count & extract
PHP Associative Array count & extract

Time:09-17

I've got the following array

$array = [
            1 => 'test',
            2 => 'test',
            3 => 'test',
            4 => 'another'
        ];

What i want to obtain from this is:

  1. The count of value 'test' $values (It's variable);
  2. After that i will need to get all keys for value 'test' do to the next assumption:
if (\count($values) > 1) {
// do something with keys of value 'test'
 echo $keysOfThatValue;
}
  1. I will need to do the upper assumption to all of the array elements grouped by array value.

CodePudding user response:

You can use array_keys with a search argument, then just count those:

$count = count($keys = array_keys($array, 'test'));

Or following your code. The if only executes if test is found and keys are returned:

if($keys = array_keys($array, 'test')) {
    // do something with $keys of value 'test'
}

CodePudding user response:

array_filter() can be used to get an array of only entries with the value "test".

  • Related