Multiple Value Match In Array Php Code Example

I need to get the keys from values that are duplicates. I tried lớn use array_search & that worked fine, BUT I only got the first value as a hit.

Bạn đang xem: Multiple value match in array php code example

I need lớn get both keys from the duplicate values, in this case 0 & 2. The search result output đầu ra as an array would be good.

Is there a PHP function to vày this or vị I need lớn write some multiple loops to vì chưng it?



You want array_keys with the tìm kiếm value

$uniqueKeys = array_unique($list<0>)foreach ($uniqueKeys as $uniqueKey) $v = array_keys($list<0>, $uniqueKey); if (count($v) > 1) foreach ($v as $key) // Work with $list<0><$key>


In array_search() we can read:

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

Xem thêm: Capabilities Là Gì, Định Nghĩa & Ý Nghĩa Của Từ Capability, Capabilities Là Gì



The following combination of function calls will give you all duplicate values:

$a = array(1, 1, 2, 3, 4, 5, 99, 2, 5, 2);$unique = array_unique($a); // preserves keys$diffkeys = array_diff_key($a, $unique);$duplicates = array_unique($diffkeys);echo "Duplicates: " . Join(" ", $duplicates) . " "; // 1 2 5
You can achieve that using array_search() by using while loop & the following workaround:

For one-multidimensional array, you may use the following function to lớn achieve that (as alternative to lớn array_keys()):

function array_isearch($str, $array) $found = array(); foreach ($array as $k => $v) if (strtolower($v) == strtolower($str)) $found<> = $k; return $found;Source: robertark,

The PHP manual states in the Return Value section of the array_search() function documentation that you can use array_keys() khổng lồ accomplish this. You just need to lớn provide the second parameter:

$userdb=Array( (0) => Array ( (uid) => "100", (name) => "Sandra Shush", (url) => "urlof100" ),);$key = array_search(100, array_column($userdb, "uid"));
Thanks for contributing an answer to Stack Overflow!

Please be sure khổng lồ answer the question. Provide details & share your research!

But avoid

Asking for help, clarification, or responding lớn other answers.Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

Post Your Answer Discard

By clicking “Post Your Answer”, you agree khổng lồ our terms of service, privacy policy & cookie policy

Not the answer you're looking for? Browse other questions tagged php arrays search duplicates key or ask your own question.

Site thiết kế / logo sản phẩm © 2022 Stack Exchange Inc; user contributions licensed under cc by-sa. Rev2022.4.8.41922

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.