php array find value in array
Find highest value in multidimensional array [duplicate]
The Problem
I have a multidimensional array similar to the one below. What I’m trying to achieve is a way to find and retrieve from the array the one with the highest «Total» value, now I know there’s a function called max but that doesn’t work with a multidimensional array like this.
What I’ve thought about doing is creating a foreach loop and building a new array with only the totals, then using max to find the max value, which would work, the only issue would then be retrieving the rest of the data which relates to that max value. I’m not sure that’s the most efficient way either.
9 Answers 9
Since PHP 5.5 you can use array_column to get an array of values for specific key, and max it.
Just do a simple loop and compare values or use array_reduce
It’s so basic algorithm.
PHP_INT_MAX;» Check the basics of finding the min number. The other option is to init it with first member of array
I know this question is old, but I’m providing the following answer in response to another question that pointed here after being marked as a duplicate. This is another alternative I don’t see mentioned in the current answers.
I know there’s a function called max but that doesn’t work with a multidimensional array like this.
You can get around that with array_column which makes getting the maximum value very easy:
Output:
Find a matching or closest value in an array
How can I search and find, for a given target value, the closest value in an array?
Let’s say I have this exemplary array:
For example, when I search with the target value 0, the function shall return 0; when I search with 3, it shall return 5; when I search with 14, it shall return 12.
16 Answers 16
Pass in the number you’re searching for as the first parameter and the array of numbers to the second:
A particular lazy approach is having PHP sort the array by the distance to the searched number:
This is high-performance function I wrote for sorted big arrays
Tested, main loop needs only
20 iterations for an array with 20000 elements.
Please mind array has to be sorted (ascending)!
Usage:
This should get you what you need.
You can simply use array_search for that, it returns one single key, if there are many instances of your search found within the array, it would return the first one it finds.
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.
Tim’s implementation will cut it most of the time. Nevertheless, for the performance cautious, you can sort the list prior to the iteration and break the search when the next difference is greater than the last.
To search the nearest value into an array of objects you can use this adapted code from Tim Cooper’s answer.
Best method I’ve found based on Piyush Dholariya’s answer:
Considering that the input array is sorted in ascending order asort() for example, you’ll be far faster to search using a dichotomic search.
Here’s a quick and dirty adaptation of some code I’m using to insert a new event in an Iterable event list sorted by DateTime objects…
Thus this code will return the nearest point at the left (before / smaller).
If you’d like to find the mathematically nearest point: consider comparing the distance of the search value with the return value and the point immediately at the right (next) of the return value (if it exists).
in_array
(PHP 4, PHP 5, PHP 7, PHP 8)
in_array — Проверяет, присутствует ли в массиве значение
Описание
Список параметров
Возвращаемые значения
Примеры
Пример #1 Пример использования in_array()
Второго совпадения не будет, потому что in_array() регистрозависима, таким образом, программа выведет:
Пример #2 Пример использования in_array() с параметром strict
Результат выполнения данного примера:
Пример #3 Пример использования in_array() с массивом в качестве параметра needle
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 38 notes
Loose checking returns some crazy, counter-intuitive results when used with certain arrays. It is completely correct behaviour, due to PHP’s leniency on variable types, but in «real-life» is almost useless.
The solution is to use the strict checking option.
// First three make sense, last four do not
If you’re working with very large 2 dimensional arrays (eg 20,000+ elements) it’s much faster to do this.
Remember to only flip it once at the beginning of your code though!
# foo it is found in the array or one of its sub array.
For a case-insensitive in_array(), you can use array_map() to avoid a foreach statement, e.g.:
Determine whether an object field matches needle.
= array( new stdClass (), new stdClass () );
$arr [ 0 ]-> colour = ‘red’ ;
$arr [ 1 ]-> colour = ‘green’ ;
$arr [ 1 ]-> state = ‘enabled’ ;
in_array() may also return NULL if the second argument is NULL and strict types are off.
If the strict mode is on, then this code would end up with the TypeError
In a high-voted example, an array is given that contains, amongst other things, true, false and null, against which various variables are tested using in_array and loose checking.
If you have an array like:
$arr = array(0,1,2,3,4,5);
Add an extra if() to adrian foeder’s comment to make it work properly:
If you found yourself in need of a multidimensional array in_array like function you can use the one below. Works in a fair amount of time
This code will search for a value in a multidimensional array with strings or numbers on keys.
I just struggled for a while with this, although it may be obvious to others.
If you have an array with mixed type content such as:
?>
be sure to use the strict checking when searching for a string in the array, or it will match on the 0 int in that array and give a true for all values of needle that are strings strings.
I found out that in_array will *not* find an associative array within a haystack of associative arrays in strict mode if the keys were not generated in the *same order*:
?>
I had wrongly assumed the order of the items in an associative array were irrelevant, regardless of whether ‘strict’ is TRUE or FALSE: The order is irrelevant *only* if not in strict mode.
I would like to add something to beingmrkenny at gmail dot com comparison post. After debugging a system, i discovered a security issue in our system and his post helped me find the problem.
In my additional testing i found out that not matter what you search for in an array, except for 0 and null, you get true as the result if the array contains true as the value.
Examples as php code :
Such the best practice in our case is to use strict mode. Which was not so obvious.
Kelvin’s case-insensitive in_arrayi is fine if you desire loose typing, but mapping strtolower onto the array will (attempt to) cast all array members to string. If you have an array of mixed types, and you wish to preserve the typing, the following will work:
// Note
// You can’t use wildcards and it does not check variable type
?>
A first idea for a function that checks if a text is in a specific column of an array.
It does not use in_array function because it doesn’t check via columns.
Its a test, could be much better. Do not use it without test.
Beware when using this function to validate user input:
$a = array(‘0’ => ‘Opt 1’, ‘1’ => ‘Opt 2’, ‘2’ => ‘Opt 3’);
$v = ‘sql injection’;
var_dump(in_array($v, array_keys($a)));
This will result : true;
If you need to find if a value in an array is in another array you can use the function:
The top voted notes talked about creating strict comparison function, because in_array is insufficient, because it has very lenient type checking (which is PHP default behaviour).
The thing is, in_array is already sufficient. Because as a good programmer, you should never have an array which contains
It’s better to fix how you store data and retrieve data from user, rather than fixing in_array() which is not broken.
If you’re creating an array yourself and then using in_array to search it, consider setting the keys of the array and using isset instead since it’s much faster.
Recursive in array using SPL
If array contain at least one true value, in_array() will return true every times if it is not false or null
Be careful to use the strict parameter with truth comparisons of specific strings like «false»:
?>
The above example prints:
False is truthy.
False is not truthy.
This function is for search a needle in a multidimensional haystack:
When using numbers as needle, it gets tricky:
Note this behaviour (3rd statement):
in_array(0, array(42)) = FALSE
in_array(0, array(’42’)) = FALSE
in_array(0, array(‘Foo’)) = TRUE
in_array(‘0’, array(‘Foo’)) = FALSE
Watch out for this:
Yes, it seems that is_array thinks that a random string and 0 are the same thing.
Excuse me, that’s not loose checking, that’s drunken logic.
Or maybe I found a bug?
hope this function may be useful to you, it checks an array recursively (if an array has sub-array-levels) and also the keys, if wanted:
If you have a multidimensional array filled only with Boolean values like me, you need to use ‘strict’, otherwise in_array() will return an unexpected result.
Hope this helps somebody, cause it took me some time to figure this out.
If you search for numbers, in_array will convert any strings in your array to numbers, dropping any letters/characters, forcing a numbers-to-numbers comparison. So if you search for 1234, it will say that ‘1234abcd’ is a match. Example:
Esta función falla con las letras acentuadas y con las eñes. Por tanto, no sirve para los caracteres UTF-8.
El siguiente código falla para na cadena = «María Mañas», no reconoce ni la «í» ni la «ñ»:
// ¿La cadena está vacía?
if (empty ($cadena))
<
$correcto = false;
>
else
<
$nombreOapellido = mb_strtoupper ($cadena, «utf-8»);
$longitudCadena = mb_strlen ($cadena, «utf-8»);
Esta función falla con las letras acentuadas y con las eñes. Por tanto, no sirve para los caracteres UTF-8.
El siguiente código falla para na cadena = «María Mañas», no reconoce ni la «í» ni la «ñ»:
// ¿La cadena está vacía?
if (empty ($cadena))
<
$correcto = false;
>
else
<
$nombreOapellido = mb_strtoupper ($cadena, «utf-8»);
$longitudCadena = mb_strlen ($cadena, «utf-8»);
I needed a version of in_array() that supports wildcards in the haystack. Here it is:
$haystack = array( ‘*krapplack.de’ );
$needle = ‘www.krapplack.de’ ;
var_dump(in_array(‘invalid’, array(0,10,20)));
The above code gives true since the ‘invalid’ is getting converted to 0 and checked against the array(0,10,20)
but var_dump(in_array(‘invalid’, array(10,20))); gives ‘false’ since 0 not there in the array
A function to check an array of values within another array.
Second element ‘123’ of needles was found as first element of haystack, so it return TRUE.
If third parameter is not set to Strict then, the needle is found in haystack eventhought the values are not same. the limit behind the decimal seems to be 6 after which, the haystack and needle match no matter what is behind the 6th.
In PHP array function the in_array() function mainly used to check the item are available or not in array.
1. Non-strict validation
2. Strict validation
1. Non-strict validation:
This method to validate array with some negotiation. And it allow two parameters.
Note: the Example 1, we use only two parameter. Because we can’t mention `false` value. Because In default the in_array() take `false` as a boolean value.
In above example,
Example 1 : The `key1` is not value in the array. This is key of the array. So this scenario the in_array accept the search key as a value of the array.
Example 2: The value `577` is not in the value and key of the array. It is some similar to the value `579`. So this is also accepted.
So this reason this type is called non-strict function.
2. Strict validation
This method to validate array without any negotiation. And it have three parameters. If you only mention two parameter the `in_array()` function take as a non-strict validation.
This is return `true` only the search string is match exactly with the array value with case sensitivity.