Viewed   112 times

I'm trying to get hold of the largest value in an array, while still preserving the item labels. I know I can do this by running sort(), but if I do so I simply lose the labels - which makes it pointless for what I need. Here's the array:

array("a"=>1,"b"=>2,"c"=>4,"d"=>5);

Any ideas?

 Answers

2

Don't sort the array to get the largest value.

Get the max value:

$value = max($array);

Get the corresponding key:

$key = array_search($value, $array);
Monday, December 19, 2022
1
function cmp($a, $b)
{

$sizes = array(
"XXS" => 0,
"XS" => 1,
"S" => 2,
"M" => 3,
"L" => 4,
"XL" => 5,
"XXL" => 6
);

$asize = $sizes[$a];
$bsize = $sizes[$b];

if ($asize == $bsize) {
    return 0;
}

return ($asize > $bsize) ? 1 : -1;
}

usort($your_array, "cmp");
Wednesday, August 24, 2022
 
enrique
 
3

Use multi-byte string functions. There is a function called strcoll which seems to suit your needs.

More info:

  • On how to sort an array of UTF-8 strings
  • How to sort an array of UTF-8 strings?

EDIT: added Peter's working code, below

setlocale(LC_COLLATE, 'sk_SK.utf8');

usort($fb_friends['data'], 'custom_sort');

function custom_sort($a, $b) {
    return strcoll ($a['last_name'], $b['last_name']);
}

foreach ($fb_friends['data'] as $friend) {
    echo '<br>';
    echo $friend['name'];
}
Wednesday, August 3, 2022
 
4

Top level:

print_r($data);
// Output: Array ( [0] => Array ( [0] => Array ( [value] => 150109 [format] => [safe_value] => 150109 ) ) )

Outmost element:

print_r($data[0]);
// Output: Array ( [0] => Array ( [value] => 150109 [format] => [safe_value] => 150109 ) )

Next level:

print_r($data[0][0]);
// Output: Array ( [value] => 150109 [format] => [safe_value] => 150109 )

The final value

echo $data[0][0]['value'];
// Output: 150109

Accessing each layer of values this way makes it easier to figure out how to get to your desired value. After a while this becomes more obvious.

Thursday, November 24, 2022
 
3

Use array_keys():

var_dump(array_keys($data));

Return all the keys or a subset of the keys of an array

Wednesday, August 10, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :