Php search in array multiple values
I need to get the keys from values that are duplicates. I tried to use array_search and that worked fine, BUT I only got the first value as a hit. Show I need to get both keys from the duplicate values, in this case 0 and 2. The search result output as an array would be good. Is there a PHP function to do this or do I need to write some multiple loops to do it?
kenorb 144k76 gold badges655 silver badges710 bronze badges asked Jul 31, 2009 at 13:42
Jens TörnellJens Törnell 21.4k43 gold badges115 silver badges188 bronze badges You want array_keys with the search value
which will return an array of the keys with the specified value, in your case [0, 2]. If you want to find the duplicates as well, you can first make a pass with array_unique, then iterate over that array using array_keys on the original; anything which returns an array of length > 1 is a duplicate, and the result is the keys in which the duplicates are stored. Something like...
answered Jul 31, 2009 at 13:46
Adam WrightAdam Wright 48.5k12 gold badges129 silver badges152 bronze badges 2 In
kenorb 144k76 gold badges655 silver badges710 bronze badges
answered Jul 31, 2009 at 13:46
1 The following combination of function calls will give you all duplicate values:
answered Jul 31, 2009 at 14:31
Till TheisTill Theis 1,23811 silver badges15 bronze badges You can achieve that using
Source: cue at openxbox at php.net For one-multidimensional array, you may use the following function to achieve that (as alternative to
Source: robertark, php.net answered Nov 8, 2015 at 19:07
kenorbkenorb 144k76 gold badges655 silver badges710 bronze badges 0
Sven Eberth 2,97112 gold badges22 silver badges27 bronze badges answered Jun 19, 2021 at 11:10
1 How do you search multiple values in an array?To check if multiple values exist in an array:
Use the every() method to iterate over the array of values. On each iteration, use the indexOf method to check if the value is contained in the other array. If all values exist in the array, the every method will return true .
How do I check if an array contains multiple values in PHP?php check if any of multiple values in array. function in_array_any($needles, $haystack) {. return ! empty(array_intersect($needles, $haystack));. echo in_array_any( [3,9], [5,8,3,1,2] ); // true, since 3 is present.. echo in_array_any( [4,9], [5,8,3,1,2] ); // false, neither 4 nor 9 is present.. How do you find the element of a multidimensional array?Multidimensional array search using array_search() method:
The array_search() is an inbuilt function which searches for a given value related to the given array column/key. This function only returns the key index instead of a search path.
How do you check if an array contains a value in PHP?The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.
|