Jump to content

Recommended Posts

Hello,

 

I have an array, and I want to search the array for a particular 'word' and return how many times that 'word' is in the array. I tried using the search_array, but that just seems to find the first 'word' and return it. What I want it this:

 

$array = array(0-blue, 1-yellow, 2-red, 3-blue, 4-blue, 5-blue, 6-yellow);

 

Lets say I want to see how many times the word 'blue' is in the array: $counter = 4;

How would I achieve this?

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/260407-php-search-array-for-same-values/
Share on other sites

Part of the issue "might" be the way you've made your array.  Here's two examples.

$search="blue";
$array = array("blue", "yellow", "red", "blue", "blue", "blue", "yellow");	

$counts= array_keys($array,$search);
$counter=count($counts);
echo " $counter";

echo "<br/>"; 
$counts2=array_count_values($array);
$counter2=$counts2[$search];
echo "$counter2";	
?>

Part of the issue "might" be the way you've made your array.  Here's two examples.

$search="blue";
$array = array("blue", "yellow", "red", "blue", "blue", "blue", "yellow");	

$counts= array_keys($array,$search);
$counter=count($counts);
echo " $counter";

echo "<br/>"; 
$counts2=array_count_values($array);
$counter2=$counts2[$search];
echo "$counter2";	
?>

 

Thanks, your first option works like a charm. Thanks!  :D

 

This doesn't let me search for a specific word/value  :confused:

 

sure it does:

 

$array = array('blue', 'yellow', 'red', 'blue', 'blue', blue', yellow');
$count_arr = array_count_values($array);
$blue_count = $count_arr['blue']; //prints 4

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.