Jump to content

PHP - Search Array For 'Same' Values


oliverj777

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.