php

PHP associative existence check


I have

$a = array('ten', 'ten', 'ten', 'three', 'two', 'one', 'ten', 'four', 'four');
$b = array_count_values($a);

I'm trying to return the number of times a particular string $c appears in $a if $c is found.

So for example:

If $c='four' then I need the output 2.

If $c='fout' then I need the output as 'not found'

I'm new to PHP and am having trouble with the syntax, especially since this is an associative array.

How do I do this?


Solution

  • The PHP Manual states that array_key_exists returns an associative array with the keys being the values and the values being the frequency. Therefore, you can check if the variable $a is a key of $b and if it is echo out the frequency count.

    $a = array('ten','ten','ten','three','two','one','ten','four','four');
    $b= array_count_values ($a);
    
    if(array_key_exists($c, $b))
    {
      echo $b[$c];
    }
    else
    {
      echo 'not found';
    }