Getting an array key using the max() function - php

I'm using the max() function to find the largest value in an array. I need a way to return the key of that value. I've tried playing with the array_keys() function, but all I can get that to do is return the largest key of the array. There has to be a way to do this but the php manuals don't mention anything.
Here's a sample of the code I'm using:
$arrCompare = array('CompareOne' => $intOne,
'CompareTwo' => $intTwo,
'CompareThree' => $intThree,
'CompareFour' => $intfour);
$returnThis = max($arrCompare);
I can successfully get the highest value of the array, I just can't get the associated key. Any ideas?
Edit: Just to clarify, using this will not work:
$max_key = max( array_keys( $array ) );
This compares the keys and does nothing with the values in the array.

array_search function would help you.
$returnThis = array_search(max($arrCompare),$arrCompare);

If you need all keys for max value from the source array, you can do:
$keys = array_keys($array, max($array));

Not a one-liner, but it will perform the required task.
function max_key($array)
{
$max = max($array);
foreach ($array as $key => $val)
{
if ($val == $max) return $key;
}
}
From http://cherryblossomweb.de/2010/09/26/getting-the-key-of-minimum-or-maximum-value-in-an-array-php/

Related

Find count of smaller no of elements in an array and the solution needs to be 2n

Hi i am stuck with a problem where in i have to find out the count of smaller no of element in an array i have implemented what we call as a brute force method but this isn't the optimised solution, can anyone help me out with the optimise solution for the code below
<?php
function find_small_count($arr){
$no_count = [];
foreach ($arr as $key => $value){
$no_count[$key] = 0;
foreach ($arr as $key1 => $value){
if ($arr[$key1] < $arr[$key]) {
$no_count[$key]++;
}
}
}
return $no_count;
}
print_r(find_small_count(['8','1','2','2','5']));
?>
Where in the expected Output should be [4,0,1,1,3]
I have three solutions for you. Let me explain
Working code sandbox
Solution 1
Use array_filter to return only qualified elements and then count the filtered array to get the count.
## Solution 1:
function find_small_count($arr)
{
$response = [];
foreach ($arr as $valueToSearch) {
$filtered = array_filter($arr, function ($value) use ($valueToSearch) {
return $value < $valueToSearch;
});
$response[] = ['valueToSearch' => $valueToSearch, 'count' => count($filtered)];
}
return $response;
}
print_r(find_small_count(['8', '1', '2', '2', '5']));
Solution 2
Sort the array in ascending order. When doing so your array has all numbers lesser than the current element appearing before it (in the array). Therefore the key for the array will be the count of all those numbers that are less than the current value, excluding the current number (keys start with 0).
Exception will be when a number appears twice, like 2 in your case. If we were to use key as the count in your case the first 2 will have count 1 and second 2 will have count 2, which is incorrect. Do note that the first 2 does give you the correct count.
To avoid this we can use array_unique and remove the duplicates. That will leave you with only one 2 in your response (the first one) and will give you the correct count.
You may think what about 5. For that we can fallback on the behavior of array_unique to preserve the keys. Hence even after array_unique 5 will retain its key, ie. 3. And our objective is accomplished. The only side effect is that the response will be [4,0,1,3] instead of [4,0,1,1,3]. So if that works you can use this method.
function find_small_count_two($arr){
$response = [];
sort($arr);
$arrUniqueAndSorted = array_unique($arr);
foreach ($arrUniqueAndSorted as $key => $value){
$response[] = ['valueToSearch' => $value, 'count' => $key];
}
return $response;
}
print_r(find_small_count_two(['8', '1', '2', '2', '5']));
Solution 3
Use array_search. From the docs
Searches the array for a given value and returns the first corresponding key if successful
Same logic as Solution 2 but this one avoids array_unique
function find_small_count_three($arr){
$response = [];
sort($arr);
foreach ($arr as $valueToCount){
$count =array_search($valueToCount, $arr);
$response[] = ['valueToSearch' => $valueToCount, 'count' => $count];
}
return $response;
}

PHP search value in an array an return parent key

i try to search through an multi-Array to get the key back:
Array:
$types = array(
'ABD' => array('value'),
'CDE' => array('from'),
'EF' => array('array', 'array2', 'array30')
)
PHP
$key = array_search('array30', $types);
this should return "EF".
thanks for help.
Try this. User a foreach loop and in_array
foreach($types as $key=>$data){
if(in_array('array30',$data)){
echo $key;
}
}
http://php.net/manual/en/function.in-array.php
get these elements have the array30 with array_filter and in_array.
var_dump(array_filter($types, function($v){in_array('array30', $v);}));
if you just want the key, use array_keys on the array_filter output.

How to remove all instances of duplicated values from an array

I know there is array_unique function, but I want to remove duplicates. Is there a built-in function or do I have to roll my own.
Example input:
banna, banna, mango, mango, apple
Expected output:
apple
You can use a combination of array_unique, array_diff_assoc and array_diff:
array_diff($arr, array_diff_assoc($arr, array_unique($arr)))
You can use
$singleOccurences = array_keys(
array_filter(
array_count_values(
array('banana', 'mango', 'banana', 'mango', 'apple' )
),
function($val) {
return $val === 1;
}
)
)
See
array_count_values — Counts all the values of an array
array_filter — Filters elements of an array using a callback function
array_keys — Return all the keys or a subset of the keys of an array
callbacks
Just write your own simple foreach loop:
$used = array();
$array = array("banna","banna","mango","mango","apple");
foreach($array as $arrayKey => $arrayValue){
if(isset($used[$arrayValue])){
unset($array[$used[$arrayValue]]);
unset($array[$arrayKey]);
}
$used[$arrayValue] = $arrayKey;
}
var_dump($array); // array(1) { [4]=> string(5) "apple" }
have fun :)
If you want to only leave values in the array that are already unique, rather than select one unique instance of each value, you will indeed have to roll your own. Built in functionality is just there to sanitise value sets, rather than filter.
You want to remove any entries that have duplicates, so that you're left with only the entries that were unique in the list?
Hmm it does sound like something you'll need to roll your own.
There is no existing function; You'll have to do this in two passes, one to count the unique values and one to extract the unique values:
$count = array();
foreach ($values as $value) {
if (array_key_exists($value, $count))
++$count[$value];
else
$count[$value] = 1;
}
$unique = array();
foreach ($count as $value => $count) {
if ($count == 1)
$unique[] = $value;
}
The answer on top looks great, but on a side note: if you ever want to eliminate duplicates but leave the first one, using array_flip twice would be a pretty simple way to do so. array_flip(array_flip(x))
Only partially relevant to this specific question - but I created this function from Gumbo's answer for multi dimensional arrays:
function get_default($array)
{
$default = array_column($array, 'default', 'id');
$array = array_diff($default, array_diff_assoc($default, array_unique($default)));
return key($array);
}
In this example, I had cached statuses and each one other than the default was 0 (the default was 1). I index the default array from the IDs, and then turn it into a string. So to be clear - the returned result of this is the ID of the default status providing it's in the same part of the multi dimensional array and not the key of it
PHP.net http://php.net/manual/en/function.array-unique.php
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
Takes an input array and returns a new array without duplicate values.
New solution:
function remove_dupes(array $array){
$ret_array = array();
foreach($array as $key => $val){
if(count(array_keys($val) > 1){
continue;
} else {
$ret_array[$key] = $val;
}
}

selecting an array key based on partial string

I have an array and in that array I have an array key that looks like, show_me_160 this array key may change a little, so sometimes the page may load and the array key maybe show_me_120, I want to now is possible to just string match the array key up until the last _ so that I can check what the value is after the last underscore?
one solution i can think of:
foreach($myarray as $key=>$value){
if("show_me_" == substr($key,0,8)){
$number = substr($key,strrpos($key,'_'));
// do whatever you need to with $number...
}
}
I ran into a similar problem recently. This is what I came up with:
$value = $my_array[current(preg_grep('/^show_me_/', array_keys($my_array)))];
you would have to iterate over your array to check each key separately, since you don't have the possibility to query the array directly (I'm assuming the array also holds totally unrelated keys, but you can skip the if part if that's not the case):
foreach($array as $k => $v)
{
if (strpos($k, 'show_me_') !== false)
{
$number = substr($k, strrpos($k, '_'));
}
}
However, this sounds like a very strange way of storing data, and if I were you, I'd check if there's not an other way (more efficient) of passing data around in your application ;)
to search for certain string in array keys you can use array_filter(); see docs
// the array you'll search in
$array = ["search_1"=>"value1","search_2"=>"value2","not_search"=>"value3"];
// filter the array and assign the returned array to variable
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($key){
return(strpos($key,'search_') !== false);
},
// flag to let the array_filter(); know that you deal with array keys
ARRAY_FILTER_USE_KEY
);
// print out the returned array
print_r($foo);
if you search in the array values you can use the flag 0 or leave the flag empty
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($value){
return(strpos($value,'value') !== false);
},
// flag to let the array_filter(); know that you deal with array value
0
);
or
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($value){
return(strpos($value,'value') !== false);
}
);
if you search in the array values and array keys you can use the flag ARRAY_FILTER_USE_BOTH
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($value, $key){
return(strpos($key,'search_') !== false or strpos($value,'value') !== false);
},
ARRAY_FILTER_USE_BOTH
);
in case you'll search for both you have to pass 2 arguments to the callback function
You can also use a preg_match based solution:
foreach($array as $str) {
if(preg_match('/^show_me_(\d+)$/',$str,$m)) {
echo "Array element ",$str," matched and number = ",$m[1],"\n";
}
}
filter_array($array,function ($var){return(strpos($var,'searched_word')!==FALSE);},);
return array 'searched_key' => 'value assigned to the key'
foreach($myarray as $key=>$value)
if(count(explode('show_me_',$event_key)) > 1){
//if array key contains show_me_
}
More information (example):
if array key contain 'show_me_'
$example = explode('show_me_','show_me_120');
print_r($example)
Array ( [0] => [1] => 120 )
print_r(count($example))
2
print_r($example[1])
120

How to search Array for multiple values in PHP?

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.
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?
$list[0][0] = "2009-09-09";
$list[0][1] = "2009-05-05";
$list[0][2] = "2009-09-09";
$list[1][0] = "first-paid";
$list[1][1] = "1";
$list[1][2] = "last-unpaid";
echo array_search("2009-09-09",$list[0]);
You want array_keys with the search value
array_keys($list[0], "2009-09-09");
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...
$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 return the keys for all
matching values, use array_keys() with
the optional search_value parameter
instead.
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) . "\n"; // 1 2 5
You can achieve that using array_search() by using while loop and the following workaround:
while (($key = array_search("2009-09-09", $list[0])) !== FALSE) {
print($key);
unset($list[0][$key]);
}
Source: cue at openxbox at php.net
For one-multidimensional array, you may use the following function to achieve that (as alternative to 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, php.net
The PHP manual states in the Return Value section of the array_search() function documentation that you can use array_keys() to accomplish this. You just need to provide the second parameter:
$keys = array_keys($list[0], "2009-09-09");
$userdb=Array
(
(0) => Array
(
(uid) => '100',
(name) => 'Sandra Shush',
(url) => 'urlof100'
),
);
$key = array_search(100, array_column($userdb, 'uid'));

Categories