开发者

php associative existence check

I have

$a = array('ten','ten','ten','three','two','one','ten','four','four');
$b= array_count_values 开发者_JAVA技巧($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 output 2

if $c='fout' Then I need 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?


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';
}


echo $b['four']; // echoes 2, since there's two 'four' values in the array.

For the custom "not found", you'd need something like:

echo isset($b['fout']) ? "it's there" : "it's not there";


$b = array_count_values($a);
$c = "four";
if (isset($b[$c]))
{
  echo $b[$c];
}
else echo "not found";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜