2

I want to see if an array has the same value multiple times,example:

$array=array('val1','val2','val3','val1');

As you can see,in the array above, there are 2 x val1 . To search if an array contains a value,i can do it with in_array:

$search=in_array('val1',$array);

And it will return true because val1 exists in array,but i need to return true if the value is found multiple times.

rvandoni
  • 3,297
  • 4
  • 32
  • 46
Petru Lebada
  • 2,167
  • 8
  • 38
  • 59

5 Answers5

7

You can exploit a lesser known feature of array_keys(), which is used to return the keys of an array as a new array (i.e. without values.)

It accepts an optional second parameter, search, that allows you to stipulate that you wish to have only those keys returned whose value corresponds to your search. So:

$arr = array('one', 'two', 'one', 'three');
$indexes = array_keys($arr, 'one'); //array(0, 2)
Mitya
  • 33,629
  • 9
  • 60
  • 107
2

By providing the search_value as second parameter to array_keys. The function will return only the keys of the array containing the value.

$array=array('val1','val2','val3','val1');
$search = array_keys($array, 'val1'); 

For reference, Please READ

Think Different
  • 2,815
  • 1
  • 12
  • 18
2

Try

<?php
$array = array('val1','val2','val3','val1');
$cnt = array_count_values($array);
echo $cnt['val1'];

https://eval.in/202593

Xrymz
  • 171
  • 3
  • your suggestion it's awesome,but i have a question if the value that im searching , is actualy a $_POST['val1'] , how should i build the syntax? $cnt($_POST['val1']) it's good? – Petru Lebada Oct 07 '14 at 12:08
  • $_POST is array, try array_count_values($_POST)['val1']; – Xrymz Oct 07 '14 at 12:10
  • if array('val1','val2','val3','val1'). in $_POST['val'] u will send something like 'val1'? – Xrymz Oct 07 '14 at 12:18
1

This function should do the trick:

function check_multi($testVal,$arr) {
   foreach($arr as $curVal) {
     $counts[$curVal]++;
   }
   if(isset($counts[$val])
     return $counts[$val];
   else
     return null
}
Youn Elan
  • 2,379
  • 3
  • 23
  • 32
1

try this

https://eval.in/202596

echo array_count_values($array)["val1"];

You will get the following array when you execute this

  • are you sure this syntax is correct? i get some syntax errors in my editor – Petru Lebada Oct 07 '14 at 11:52
  • @Petru - what version of PHP are you using? This is array dereferencing, which was introduced in PHP 5.4.0 – Mark Baker Oct 07 '14 at 11:53
  • @PetruLebada Try [this](http://php.net/manual/en/function.array-count-values.php#refsect1-function.array-count-values-examples) You will understand. –  Oct 07 '14 at 11:54