Как найти одинаковые значения в массиве php

Performance-Optimized Solution

If you care about performance and micro-optimizations, check this one-liner:

function no_dupes(array $input_array) {
    return count($input_array) === count(array_flip($input_array));
}

Description:
Function compares number of array elements in $input_array with array_flip’ed elements. Values become keys and guess what — keys must be unique in associative arrays so not unique values are lost and final number of elements is lower than original.

Warning:
As noted in the manual, array keys can be only type of int or string so this is what you must have in original array values to compare, otherwise PHP will start casting with unexpected results. See https://3v4l.org/7bRXI for an example of this fringe-case failure mode.

Proof for an array with 10 million records:

  • The top-voted solution by Jason McCreary: 14.187316179276s 🐌🐌🐌🐌🐌🐌🐌🐌🐌🐌🐌🐌🐌🐌
  • The accepted solution by Mike Sherov: 2.0736091136932s 🐌🐌
  • This answer’s solution: 0.14155888557434s 🐌/10

Test case:

<?php

$elements = array_merge(range(1,10000000),[1]);

$time = microtime(true);
accepted_solution($elements);
echo 'Accepted solution: ', (microtime(true) - $time), 's', PHP_EOL;

$time = microtime(true);
most_voted_solution($elements);
echo 'Most voted solution: ', (microtime(true) - $time), 's', PHP_EOL;

$time = microtime(true);
this_answer_solution($elements);
echo 'This answer solution: ', (microtime(true) - $time), 's', PHP_EOL;

function accepted_solution($array){
 $dupe_array = array();
 foreach($array as $val){
  // sorry, but I had to add below line to remove millions of notices
  if(!isset($dupe_array[$val])){$dupe_array[$val]=0;}
  if(++$dupe_array[$val] > 1){
   return true;
  }
 }
 return false;
}

function most_voted_solution($array) {
   return count($array) !== count(array_unique($array));
}

function this_answer_solution(array $input_array) {
    return count($input_array) === count(array_flip($input_array));
}

Notice that accepted solution might be faster in certain condition when not unique values are near the beginning of huge array.

I am working with a one dimensional array in PHP. I would like to detect the presence of duplicate values, then count the number of duplicate values and output the results. For example, given the following array:

$array = [
    'apple',
    'orange',
    'pear',
    'banana',
    'apple',
    'pear',
    'kiwi',
    'kiwi',
    'kiwi'
];

I would like to print:

apple (2)
orange
pear (2)
banana
kiwi (3)

Any advice on how to approach this problem?

mickmackusa's user avatar

mickmackusa

43.1k12 gold badges80 silver badges132 bronze badges

asked Jul 23, 2009 at 10:11

mikey_w's user avatar

You can use array_count_values function

$array = array('apple', 'orange', 'pear', 'banana', 'apple',
'pear', 'kiwi', 'kiwi', 'kiwi');

print_r(array_count_values($array));

will output

Array
(
   [apple] => 2
   [orange] => 1
   [pear] => 2
   etc...
)

Gagantous's user avatar

Gagantous

4126 gold badges28 silver badges67 bronze badges

answered Jul 23, 2009 at 10:14

Silfverstrom's user avatar

SilfverstromSilfverstrom

28k6 gold badges45 silver badges57 bronze badges

1

if(count(array_unique($array))<count($array))
{
    // Array has duplicates
}
else
{
    // Array does not have duplicates
}

2

function array_not_unique( $a = array() )
{
    return array_diff_key( $a , array_unique( $a ) );
}

Result: (Demo)

array (
  4 => 'apple',
  5 => 'pear',
  7 => 'kiwi',
  8 => 'kiwi',
)

mickmackusa's user avatar

mickmackusa

43.1k12 gold badges80 silver badges132 bronze badges

answered Oct 22, 2009 at 18:50

Anton Maryanov's user avatar

2

You could try turning that array into a associative array with the fruits as keys and the number of occurrences as values. Bit long-winded, but it looks like:

$array = array('apple', 'orange', 'pear', 'banana', 'apple',
   'pear', 'kiwi', 'kiwi', 'kiwi');
$new_array = array();
foreach ($array as $key => $value) {
    if(isset($new_array[$value]))
        $new_array[$value] += 1;
    else
        $new_array[$value] = 1;
}
foreach ($new_array as $fruit => $n) {
    echo $fruit;
    if($n > 1)
        echo "($n)";
    echo "<br />";
}

answered Jul 23, 2009 at 10:36

Simon Scarfe's user avatar

Simon ScarfeSimon Scarfe

9,3184 gold badges28 silver badges32 bronze badges

1

To get rid use array_unique(). To detect if have any use count(array_unique()) and compare to count($array).

aksu's user avatar

aksu

5,2115 gold badges23 silver badges39 bronze badges

answered Aug 20, 2009 at 15:04

Perhaps something like this (untested code but should give you an idea)?

$new = array();

foreach ($array as $value)
{
    if (isset($new[$value]))
        $new[$value]++;
    else
        $new[$value] = 1;
}

Then you’ll get a new array with the values as keys and their value is the number of times they existed in the original array.

answered Jul 23, 2009 at 10:17

1

Stuff them into a map (pseudocode)

map[string -> int] $m
foreach($word in $array)
{
    if(!$m.contains($word))
        $m[$word] = 0;

    $m[$word] += 1;
}

answered Jul 23, 2009 at 10:15

Anton Gogolev's user avatar

Anton GogolevAnton Gogolev

113k38 gold badges197 silver badges287 bronze badges

I didn’t find the answer I was looking for, so I wrote this function. This will make an array that contains only the duplicates between the two arrays, but not print the number of times an element is duplicated, so it’s not directly answering the question, but I’m hoping it’ll help someone in my situation.

function findDuplicates($array1,$array2)
{
    $combined = array_merge($array1,$array2);
    $counted = array_count_values($combined);
    $dupes = [];
    $keys = array_keys($counted);
    foreach ($keys as $key)
    {   
        if ($counted[$key] > 1)
        {$dupes[] = $key;}
    }
    sort($dupes);
    return $dupes;
}
$array1 = [1,2,3,4,5];
$array2 = [4,5,6,7,8];
$dupes = findDuplicates($array1,$array2);
print_r($dupes);

Outputs:

Array
(
    [0] => 4
    [1] => 5
)

answered Mar 15, 2018 at 20:02

aswine's user avatar

aswineaswine

16911 bronze badges

$data = ['outer', 'inner', 'sole', 'sole', 'outer', 'outer'];

$result = max(array_count_values($data));

if($result > 1) {
  echo 'Duplicate items were found!';
}

I think this way is shorter and cleaner.

answered Sep 10, 2021 at 11:17

Santiago Brot's user avatar

1

function array_not_unique(array $array): array
    {
        $duplicate_array = array_diff_key( $array , array_unique( $array ) );
        $unique_array = [];
        foreach ($array as $key => $value) {
            if ( in_array($value, $duplicate_array)) {
                $duplicate_array[$key] = $value;
            }
            else {
                $unique_array[$key] = $value;
            } 

        }

        return ["unique_array" => $unique_array, "duplicate_array" => $duplicate_array];
    }

answered Oct 7, 2021 at 12:02

Rupess's user avatar

This function give you the redundant values only

function array_find_redundant($A){
    $U=$N=[];
    foreach($A As $k=>$v){
        if(in_array($v,$U)){$N[$k]=$v;}else{$U[]=$v;}
    }
    return $N;
}

$A = ['A','B','B','C','C','C'];
$B = array_find_redundant($A); // [2=>'B',4=>'C',5=>'C'] 

answered Apr 18, 2022 at 8:31

Saif's user avatar

SaifSaif

291 silver badge5 bronze badges

$arr = [1,2,2,2,4,5,5,5,8,9,10,2,5,9,10,10];
array_count_values($arr); 
// OUT PUT Array(
//    2 => 4
//    5 => 4
//    9 => 2
//   10 => 3
// )

// If you want unique items
$items = array_keys( array_intersect( array_count_values($arr), [1] ) )

//If you want duplicate items 
$duplicates = array_keys( array_diff( array_count_values($arr), [1] ) )

answered Apr 1 at 13:39

babak-maziar's user avatar

$count = 0;
$output ='';
$ischeckedvalueArray = array();
for ($i=0; $i < sizeof($array); $i++) {
    $eachArrayValue = $array[$i];
    if(! in_array($eachArrayValue, $ischeckedvalueArray)) {
        for( $j=$i; $j < sizeof($array); $j++) {
            if ($array[$j] === $eachArrayValue) {
                $count++;
            }
        }
        $ischeckedvalueArray[] = $eachArrayValue;
        $output .= $eachArrayValue. " Repated ". $count."<br/>";
        $count = 0;
    }

}

echo $output;

Tunaki's user avatar

Tunaki

132k46 gold badges331 silver badges417 bronze badges

answered Apr 16, 2016 at 18:47

uday's user avatar

Loop over the keys and values returned by array_count_values() and conditionally print the number of occurrences if greater than one.

Code: (Demo)

foreach (array_count_values($array) as $value => $count) {
    printf("%s%sn", $value, $count > 1 ? " ($count)" :'');
}

answered Apr 2 at 6:09

mickmackusa's user avatar

mickmackusamickmackusa

43.1k12 gold badges80 silver badges132 bronze badges

A simple method:

$array = array_values(array_unique($array, SORT_REGULAR));

biruk1230's user avatar

biruk1230

2,9944 gold badges16 silver badges29 bronze badges

answered Jan 28, 2020 at 13:39

thelife's user avatar

1

Оказывается, очень частая задача в тестовых заданиях соискателей — это поиск дубля в массиве. В зависимости от нюансов конкретного задания, могут просить:

  • найти все дубли или один единственный дубль;
  • использовать в решении самый быстрый алгоритм;
  • найти вообще все повторяющиеся варианты.

Я рассмотрю здесь частное решение (целых три варианта), которое вы подкрутите для своего случая. Это поиск единственного дубля в массиве чисел.

Итак, пусть $A — произвольный массив чисел. Напишем функцию, которая ищет близнеца или возвращает FALSE.

Скоростной вариант

Самый первый и самый быстрый вариант поиска — это положиться только на функции PHP без каких либо свои циклов и ветвлений.

function array_find_twins($A) {

   $N = array_flip(array_count_values($A));

   return isset($N[2]) ? $N[2] : FALSE;

}

Мы посчитали число значений, а потом просто вывернули массив. Если дублей было несколько — останется только один. Если нужно другое число повторений — используйте другой ключ на выходе (не 2, а 3, 4..).

PHP гораздо быстрее работает внутри собственных откомпилированных функций, нежели с вашими алгоритмами, какими бы они не были гениальными.

Вариант с сортировкой

Здесь мы сортируем массив, чтобы потом «вручную» просканировать его и найти рядом стоящих близнецов.

Так мы обнаружим любое повторяющееся произвольное число раз значение (т.е. тройняшек,  и т.д.)

function array_find_twins2($A) {

   sort($A, SORT_NUMERIC);

   $last = 1;

   foreach($A as $value) {

      if ($last == $value) {

         return $value;

      }

      $last = $value;

   }

   return FALSE;

}

Если по условиям задачи массив уже отсортирован, то sort() можно убрать. Останется сканер массива, быстродействие которого линейно зависит от размеров массива.

В среднем, этот вариант в 2-3 раза медленнее предыдущего (на диапазоне от 1к до 100 к элементов).

Перекладываем из одной корзины в другую

Самый тормозной, неэффективный из трех.

Мы перебираем вх. массив ($A), складывая элементы в другой ($B). Но если в нем ($B) уже есть искомое значение, то вуаля! мы нашли близнеца.

function array_find_twins3($A) {

   $B = array();

   $last = 1;

   foreach($A as $value) {

      if (in_array($value, $B)) return $value;

      $B[] = $value;

   }

   return FALSE;

}

В некоторых случаях, такая конструкция бывает востребована. Например, когда вы должны провести какие вычисления с каждым элементом, а потом уже принимать решение об эквивалентности.

Этот вариант  на 2 порядка хуже первого решения.

Если у вас есть другие варианты — присылайте :).

Написать комментарий


Данная запись опубликована в 20.06.2017 23:26 и размещена в PHP.
Вы можете перейти в конец страницы и оставить ваш комментарий.

Мало букафф? Читайте есчо !

Вызов замыкания из другой анонимной функции.

Декабрь 14, 2020 г.

При необходимости использовать (в PHP коде) замыкание (closure) A в коде замыкания B, возникает проблема в области видимости. Т.к. внутри B о функции A ничего не известно.

Пример ситуации:

[crayon-646e4039bacc3931438721/]

Для того чтобы в …

Читать

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

array_searchSearches the array for a given value and returns the first corresponding key if successful

Description

array_search(mixed $needle, array $haystack, bool $strict = false): int|string|false

Parameters

needle

The searched value.

Note:

If needle is a string, the comparison is done
in a case-sensitive manner.

haystack

The array.

strict

If the third parameter strict is set to true
then the array_search() function will search for
identical elements in the
haystack. This means it will also perform a
strict type comparison of the
needle in the haystack,
and objects must be the same instance.

Return Values

Returns the key for needle if it is found in the
array, false otherwise.

If needle is found in haystack
more than once, the first matching key is returned. To return the keys for
all matching values, use array_keys() with the optional
search_value parameter instead.

Warning

This function may
return Boolean false, but may also return a non-Boolean value which
evaluates to false. Please read the section on Booleans for more
information. Use the ===
operator for testing the return value of this
function.

Examples

Example #1 array_search() example


<?php
$array
= array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>

See Also

  • array_keys() — Return all the keys or a subset of the keys of an array
  • array_values() — Return all the values of an array
  • array_key_exists() — Checks if the given key or index exists in the array
  • in_array() — Checks if a value exists in an array

turabgarip at gmail dot com

6 years ago


About searcing in multi-dimentional arrays; two notes on "xfoxawy at gmail dot com";

It perfectly searches through multi-dimentional arrays combined with array_column() (min php 5.5.0) but it may not return the values you'd expect.

<?php array_search($needle, array_column($array, 'key')); ?>

Since array_column() will produce a resulting array; it won't preserve your multi-dimentional array's keys. So if you check against your keys, it will fail.

For example;

<?php
$people
= array(
 
2 => array(
   
'name' => 'John',
   
'fav_color' => 'green'
 
),
 
5=> array(
   
'name' => 'Samuel',
   
'fav_color' => 'blue'
 
)
);
$found_key = array_search('blue', array_column($people, 'fav_color'));
?>

Here, you could expect that the $found_key would be "5" but it's NOT. It will be 1. Since it's the second element of the produced array by the array_column() function.

Secondly, if your array is big, I would recommend you to first assign a new variable so that it wouldn't call array_column() for each element it searches. For a better performance, you could do;

<?php
$colors
= array_column($people, 'fav_color');
$found_key = array_search('blue', $colors);
?>


cue at openxbox dot com

19 years ago


If you are using the result of array_search in a condition statement, make sure you use the === operator instead of == to test whether or not it found a match.  Otherwise, searching through an array with numeric indicies will result in index 0 always getting evaluated as false/null.  This nuance cost me a lot of time and sanity, so I hope this helps someone.  In case you don't know what I'm talking about, here's an example:

<?php

$code
= array("a", "b", "a", "c", "a", "b", "b"); // infamous abacabb mortal kombat code :-P

// this is WRONG

while (($key = array_search("a", $code)) != NULL)

{

// infinite loop, regardless of the unset

unset($code[$key]);

}
// this is _RIGHT_

while (($key = array_search("a", $code)) !== NULL)

{

// loop will terminate

unset($code[$key]);

}

?>


stefano@takys dot it

12 years ago


for searching case insensitive better this:

<?php

array_search
(strtolower($element),array_map('strtolower',$array));

?>


RichGC

17 years ago


To expand on previous comments, here are some examples of
where using array_search within an IF statement can go
wrong when you want to use the array key thats returned.

Take the following two arrays you wish to search:

<?php
$fruit_array
= array("apple", "pear", "orange");
$fruit_array = array("a" => "apple", "b" => "pear", "c" => "orange");

if (

$i = array_search("apple", $fruit_array))
//PROBLEM: the first array returns a key of 0 and IF treats it as FALSEif (is_numeric($i = array_search("apple", $fruit_array)))
//PROBLEM: works on numeric keys of the first array but fails on the secondif ($i = is_numeric(array_search("apple", $fruit_array)))
//PROBLEM: using the above in the wrong order causes $i to always equal 1if ($i = array_search("apple", $fruit_array) !== FALSE)
//PROBLEM: explicit with no extra brackets causes $i to always equal 1if (($i = array_search("apple", $fruit_array)) !== FALSE)
//YES: works on both arrays returning their keys
?>


thinbegin at gmail dot com

5 years ago


Despite PHP's amazing assortment of array functions and juggling maneuvers, I found myself needing a way to get the FULL array key mapping to a specific value. This function does that, and returns an array of the appropriate keys to get to said (first) value occurrence.

function array_recursive_search_key_map($needle, $haystack) {
    foreach($haystack as $first_level_key=>$value) {
        if ($needle === $value) {
            return array($first_level_key);
        } elseif (is_array($value)) {
            $callback = array_recursive_search_key_map($needle, $value);
            if ($callback) {
                return array_merge(array($first_level_key), $callback);
            }
        }
    }
    return false;
}

usage example:
-------------------

$nested_array = $sample_array = array(
    'a' => array(
        'one' => array ('aaa' => 'apple', 'bbb' => 'berry', 'ccc' => 'cantalope'),
        'two' => array ('ddd' => 'dog', 'eee' => 'elephant', 'fff' => 'fox')
    ),
    'b' => array(
        'three' => array ('ggg' => 'glad', 'hhh' => 'happy', 'iii' => 'insane'),
        'four' => array ('jjj' => 'jim', 'kkk' => 'kim', 'lll' => 'liam')
    ),
    'c' => array(
        'five' => array ('mmm' => 'mow', 'nnn' => 'no', 'ooo' => 'ohh'),
        'six' => array ('ppp' => 'pidgeon', 'qqq' => 'quail', 'rrr' => 'rooster')
    )
);

$search_value = 'insane';

$array_keymap = array_recursive_search_key_map($search_value, $nested_array);

var_dump($array_keymap);
// Outputs:
// array(3) {
// [0]=>
//  string(1) "b"
//  [1]=>
//  string(5) "three"
//  [2]=>
//  string(3) "iii"
//}

----------------------------------------------

But again, with the above solution, PHP again falls short on how to dynamically access a specific element's value within the nested array. For that, I wrote a 2nd function to pull the value that was mapped above.

function array_get_nested_value($keymap, $array)
{
    $nest_depth = sizeof($keymap);
    $value = $array;
    for ($i = 0; $i < $nest_depth; $i++) {
        $value = $value[$keymap[$i]];
    }

    return $value;
}

usage example:
-------------------
echo array_get_nested_value($array_keymap, $nested_array);   // insane


opencart dot ocfilter at gmail dot com

1 year ago


Be careful!

<?php

var_dump

(array_search('needle', [ 0 => 0 ])); // int(0) (!)var_dump(array_search('needle', [ 0 => 0 ], true)); // bool(false)?>

But, in php 8

<?php

var_dump

(array_search('needle', [ 0 => 0 ])); // bool(false)?>


maciej at speccode dot com

7 years ago


FYI, remember that strict mode is something that might save you hours.

If you're searching for a string and you have a "true" boolean on the way - you will get it as result (first occurrence). Example below:

<?php

$arr

= [
   
'foo'    => 'bar',
   
'abc'    => 'def',
   
'bool'   => true,
   
'target' => 'xyz'
];var_dump( array_search( 'xyz', $arr ) ); //bool
var_dump( array_search( 'xyz', $arr, true ) ); //target?>


azaozz, gmail

14 years ago


Expanding on the comment by hansen{}cointel.de:

When searching for a string and the array contains 0 (zero), the string is casted to (int) by the type-casting which is always 0 (perhaps the opposite is the proper behaviour, the array value 0 should have been casted to string). That produces unexpected results if strict comparison is not used:

<?php
$a
= array(0, "str1", "str2", "str3");
echo
"
str1 = "
.array_search("str1", $a).",
str2 = "
.array_search("str2", $a).",
str3 = "
.array_search("str3", $a).",

str1 strict = "

.array_search("str1", $a, true).",
str2 strict = "
.array_search("str2", $a, true).",
str3 strict = "
.array_search("str3", $a, true);
?>

This will return:
str1 = 0, str2 = 0, str3 = 0, str1 strict = 1, str2 strict = 2, str3 strict = 3


codeslinger at compsalot dot com

13 years ago


one thing to be very aware of is that array_search() will fail if the needle is a string and the array itself contains values that are mixture of numbers and strings.  (or even a string that looks like a number)

The problem is that unless you specify "strict" the match is done using ==    and in that case any string will match a numeric value of zero which is not what you want.

-----

also, php can lookup an index pretty darn fast.  for many scenarios, it is practical to maintain multiple arrays, one in which the index of the array is the search key and the normal array that contains the data.

<?php

  $normal

[$index] = array('key'=>$key, 'data'=>'foo');

 
$inverse[$key] = $index;
//very fast lookup, this beats any other kind of search
if (array_key_exists($key, $inverse))

  {

   
$index = $inverse[$key];

    return
$normal[$index];

  }
?>


n-regen

14 years ago


If you only know a part of a value in an array and want to know the complete value, you can use the following function:
<?php
function array_find($needle, $haystack)
{
   foreach (
$haystack as $item)
   {
      if (
strpos($item, $needle) !== FALSE)
      {
         return
$item;
         break;
      }
   }
}
?>
The function returns the complete first value of $haystack that contains $needle.

andreas dot damm at maxmachine dot de

15 years ago


Combining syntax of array_search() and functionality of array_keys() to get all key=>value associations of an array with the given search-value:
<?php
function array_search_values( $m_needle, $a_haystack, $b_strict = false){
    return
array_intersect_key( $a_haystack, array_flip( array_keys( $a_haystack, $m_needle, $b_strict)));
}
?>

Usage:
<?php
$array1
= array( 'pre'=>'2', 1, 2, 3, '1', '2', '3', 'post'=>2);
print_r( array_search_values( '2', $array1));
print_r( array_search_values( '2', $array1, true));
print_r( array_search_values( 2, $array1, true));
?>

Will return:
array(4) {
    ["pre"] =>
    string(1) "2"
    [1] =>
    int(2)
    [4] =>
    string(1) "2"
    ["post"] =>
    int(2)
}
array(2) {
    ["pre"] =>
    string(1) "2"
    [4] =>
    string(1) "2"
}
array(2) {
    [1] =>
    int(2)
    ["post"] =>
    int(2)
}

yasien dot dwieb at gmail dot com

3 years ago


Beware when using array_search to a mix of string and integer where prefixes of keys may collide, as in my case I have encountered the following situation:

Assume you have the following array:
<?php
$arr
= [
          
1 => 'index 0',
          
2 => 'index 1',
          
3 => 'index 2',
          
'3anothersuffix' => 'index 3'
];$index1 = array_search('3', array_keys($arr)); // 2
$index2 = array_search('3anothersuffix', array_keys($arr)); //2
?>

$index1 and $index2 will be the same

after using strict type search:

<?php
$index1
= array_search('3', array_keys($arr), true); // false
$index2 = array_search('3anothersuffix', array_keys($arr), true);  //3
?>

it will not find $index1 at all while returning a correct value for $index2;


stooshie at gmail dot com

11 years ago


Example of a recursive binary search that returns the index rather than boolean.
<?php
// returns the index of needle in haystack
function binSearch($needle, $haystack)
{
   
// n is only needed if counting depth of search
   
global $n;
   
$n++;
   
// get the length of passed array
   
$l = count($haystack);
   
// if length is 0, problem
   
if($l <= 0)
    {
        return -
1;
    }
   
// get the mid element
   
$m = (($l+($l%2))/2);
   
// if mid >= length (e.g. l=1)
   
if($m >= $l)
    {
       
$m = $m-1;
    }
   
// get the indexed element to compare to the passed element and branch accordingly
   
$compare = $haystack[$m];
    switch(
true)
    {
        case(
$compare>$needle):
        {
           
// recurse on the lower half
           
$new_haystack = array_slice($haystack, 0, $m);
           
$c = count($new_haystack);
           
$r = binSearch($needle, $new_haystack);
           
// return current index - (length of lower half - found index in lower half)
           
return $m - ($c - $r);
            break;
        }
        case(
$compare<$needle):
        {
           
// recurse on the upper half
           
$new_haystack = array_slice($haystack, $m, ($l-$m));
           
$c = count($new_haystack);
           
$r = binSearch($needle, $new_haystack);
           
// return current position + found index in upper half
           
return $m + $r;
            break;
        }
        case(
$compare==$needle):
        {
           
// found it, so return index
           
return $m;
            break;
        }
    }
}
?>

helenadeus at gmail dot com

14 years ago


I was trying to use array_search to retrieve all the values that match a given needle, but it turns out only the first match key is returned. I built this little function, which works just like array_search, but returns all the keys that match a given needle instead. The output is an array.

<?php

$haystack

= array('a','b','a','b');$needle = 'a';print_r(array_search_all($needle, $haystack));//Output will be
// Array
// (
//         [0]=>1
//         [1]=>3
// )
function array_search_all($needle, $haystack)
{
#array_search_match($needle, $haystack) returns all the keys of the values that match $needle in $haystackforeach ($haystack as $k=>$v) {

            if(

$haystack[$k]==$needle){$array[] = $k;
        }
    }
    return (
$array);

    }

?>


nordseebaer at gmx dot de

3 years ago


It's really important to check the return value is not false! I used array_search() to determine the index of an value to unset this value and then realized that $arr[false] === $arr[0] !

<?php
$arr
= ['apple', 'banana'];var_dump($arr[0] === 'apple'); // true
var_dump($arr[false] === $arr[0]); // true
var_dump($arr[false] === 'apple'); // trueunset($arr[array_search('banana', $arr)]); //index = 1
var_dump($arr);// result
//   array(1) {
//     [0]=>
//     string(5) "apple"
//   }
unset($arr[array_search('peach', $arr)]); //not found, result is false
var_dump($arr);// result
//   array(0) {
//   }
// because $arr[false] === $arr[0]
?>

So always check the return of array_search!


kermes [at] thesevens [dot] net

15 years ago


A variation of previous searches that returns an array of keys that match the given value:

<?php
function array_ksearch($array, $str)
{
   
$result = array();
    for(
$i = 0; $i < count($array); next($array), $i++)
        if(
strtolower(current($array)) == strtolower($str))
           
array_push($result, key($array);

        return

$result;
}
?>

Usage would be as follows:
<?php
$testArray
= array('one' => 'test1', 'two' => 'test2', 'three' => 'test1', 'four' => 'test2', 'five' => 'test1');
   
print_r(array_ksearch($testArray, 'test1'));
?>


Небольшой совет: всегда давайте контекст в котором вы решаете задачу, иначе вы можете решать какую-то свою придуманную проблему, а настоящая задача совсем решается по-другому.
По поводу вашего вопроса — читайте документацию, там все есть:

php > $one = ['red']; $two = ['red', 'green', 'blue']; $three = ['red', 'blue'];
php > var_dump(array_intersect($one, $two, $three));
array(1) {
  [0]=>
  string(3) "red"
}

Вам остается в цикле подсчитать кол-во комбинаций из 10 по 3 и использовать вышеприведенную функцию, либо сообщить нам о том, что вы все-таки пытаетесь сделать и тогда, наверняка, найдется менее костыльное решение.

Понравилась статья? Поделить с друзьями:
  • Как найти подчеркивание в ворде
  • Квашеная капуста очень соленая как исправить
  • Как найти игру в дай лайт
  • Как найти зайца на горе
  • Как составить минусовую смету