Paul Duncan
Paul Duncan

Reputation: 322

PHP Count Number of Times A String Appears As A Value Inside An Array

So I looked around here for a bit but cant seem to get this right, so I am forced to make a new post. I gave it an effort! Don't hurt me.

Sample Array:

$ndata = Array
(
    [ARMOR_HEAD] => Andariel's Visage
    [ARMOR_TORSO] => Blackthorne's Surcoat
    [ARMOR_FEET] => Illusory Boots
    [ARMOR_HANDS] => Gauntlets of Akkhan
    [ARMOR_SHOULDERS] => Pauldrons of Akkhan
    [ARMOR_LEGS] => Blackthorne's Jousting Mail
    [ARMOR_BRACERS] => Nemesis Bracers
    [ARMOR_MAINHAND] => Gyrfalcon's Foote
    [ARMOR_OFFHAND] => Jekangbord
    [ARMOR_WAIST] => Blackthorne's Notched Belt
    [ARMOR_RRING] => Ring of Royal Grandeur
    [ARMOR_LRING] => Stone of Jordan
    [ARMOR_NECK] => Kymbo's Gold
)

  $count = count(preg_grep('Akkhan', $ndata));
  print_r($count);

So this is only returns 1 instead of 2. I also tried array_search(), but that simply returns a the first found with its key. Or in_array but that is just boolean I guess.. Is there a better way to go about this?

Upvotes: 0

Views: 173

Answers (1)

eagle12
eagle12

Reputation: 1668

The first parameter to preg_grep is not a string, it is a regular expression pattern represented as a string. Try this:

preg_grep('/Akkhan/i', $ndata)

For more information, see the documentation page for preg_grep.

Upvotes: 2

Related Questions