Finding the minimum value's key in an associative array - php

In PHP, say that you have an associative array like this:
$pets = array(
"cats" => 1,
"dogs" => 2,
"fish" => 3
);
How would I find the key with the lowest value? Here, I'd be looking for cats.
Is there some built in PHP function that I've missed which does this? It would also be great if there was a solution that accounted for several values being identical, as below:
$pets = array(
"cats" => 1,
"dogs" => 1,
"fish" => 2
);
Above, I wouldn't mind if it just output either; cats or dogs.
Thanks in advance.

array_keys is your friend:
$pets = array(
"cats" => 1,
"dogs" => 2,
"fish" => 3
);
array_keys($pets, min($pets)); # array('cats')
P.S.: there is a dup here somewhere on SO (it had max instead of min, but I can distinctly remember it).

Thats how i did it.
$pets = array(
"cats" => 1,
"dogs" => 2,
"fish" => 3
);
array_search(min($pets), $pets);
I hope that helps

Might try looking into these:
natcasesort(array)
natsort(array)

$min_val = null;
$min_key = null;
foreach($pets as $pet => $val) {
if ($val < $min_val) {
$min_val = $min;
$min_key = $key;
}
}
You can also flip the array and sort it by key:
$flipped = array_flip($pets);
ksort($flipped);
Then the first key is the minimum, and its value is the key in the original array.

Another approach for retrieving a single string is by using a desirable sorting method and retrieving the first key directly by using key() on the sorted array. In this instance the key with the lowest value is desired, asort will sort from lowest to highest values and reset the internal pointer. To retrieve the reverse (highest to lowest) use arsort.
Example: https://3v4l.org/5ijPh
$pets = array(
"dogs" => 2,
"cats" => 1,
"fish" => 3
);
asort($pets);
var_dump(key($pets));
//string(4) "cats"
$pets = array(
"dogs" => 1,
"cats" => 1,
"fish" => 3
);
asort($pets);
var_dump(key($pets));
//string(4) "dogs"
Take note that all of the PHP array sorting methods will alter the array by-reference.
To prevent altering the original array, create a copy of the array or use an Iterator.
$petsSorted = $pets;
asort($petsSorted);
key($petsSorted);

find the highest value
print max(120, 7, 8, 50);
returns --> 120
$array = array(100, 7, 8, 50, 155, 78);
print max($array);
returns --> 155
find the lowest value
print min(120, 7, 8, 50);
returns --> 7
$array = array(50, 7, 8, 101, 5, 78);
print min($array);
returns --> 5

Related

php Sorting an array based upon key value of another array

I have one array:
$array_sorter = [
'XXS' => 1,
'XS' => 2,
'S' => 3,
'M' => 4,
'L' => 5,
'XL' => 6,
'XXL' => 7
];
and another one that could be like this:
$array_to_sort = ('XS','M','XL','S','L','XXS')
how can I do to sort the second one based upon the first one?
I mean:
$array_to_sort are sizes but they are random inside this array
I need to print the list of available sizes ($array_to_sort) but in the order of $array_sorter
As stated by #Jakumi, usort would be the way to go. However this way might be easier to understand if you are a beginner :
$array_sorter = [
'XXS' => 1,
'XS' => 2,
'S' => 3,
'M' => 4,
'L' => 5,
'XL' => 6,
'XXL' => 7,
];
$array_to_sort = array('XS', 'M', 'XL', 'S', 'L', 'XXS');
$array_sorted = array();
foreach($array_to_sort as $item){
$k = $array_sorter[$item];
$array_sorted[$k] = $item;
}
ksort($array_sorted);
Simply use the first array as a "weight"-provider. I mean the first array have a weight for every entry of your second array (e.g. M get the weight 4).
loop over the second array and create a thrid one: $weightArray like this:
$weightArray = array();
foreach($array_to_sort as $value){
$weight = $array_sorter[$value];
if(!isset($weightArray[$weight])){
$weightArray[$weight] = array();
}
$weightArray[$weight][] = $value;
}
Now you have an array like this: (2=>'XS', 4=>'M', 5=>'XL', 3=>'S', 5=>'L', 1=>'XXS')
now you can sort it by key ksort() and copy it back to your source array like this:
$array_to_sort = array_values(ksort($weightArray));
PS: if you have something like $array_to_sort = ('XS','M','M','M','L','XXS') it will also work => $array_to_sort = ('XXS','XS','M','M','M','L')
Thanks to all for you suggestion
I found alone this solution:
my mistake was focusing on the array to be sorted ($arrat_to_sort)
instead I turned the problem:
as $array_sorter always contains all possible values of $arrat_to_sort
in the right order, I used the function array_intersect($ array_sorter, $ arrat_to_sort)
and immediately I have an array with the values of $ arrat_to_sort in the $array_sorter position

declaring 3d array in php

I need to declare (not define) three dimensional array in PHP and then assign values to it.
For example,
<?php
$item = array(
array("item1", 22, 18),
array("Item2", 15, 13),
array("Item3", 5, 2),
);
?>
This is how I want my array. I first want to declare this $item array and then assign those three values (e.g item1, 22, 18) to it. Please help me with this and also how to access this array.
You said you wanted a three-dimensional array. The current array you have is two-dimensional.
What you might have meant was to have "item#" as a key to your array.
<?php
$item = array(
"item1" => array( 22, 18 ),
"Item2" => array( 15, 13 ),
"Item3" => array( 5, 2 ),
);
?>
You would access an element with $item['item1'], which would give you the array (22,18)

PHP Get minimum value of a key in array of arrays

I have an array like this:
$array = array(
array('id' => 1, 'quantity' => 10),
array('id' => 2, 'quantity' => 25),
array('id' => 3, 'quantity' => 38),
...
);
I want to find the array contains minimum of quantity. How can I do it simply in one two lines of code?! (I prefer to use PHP functions)
Also if the variable is an Object, Does it make any difference?!
Like this:
usort($array,function($a,$b) {return $a['quantity']-$b['quantity'];});
return $array[0];
If needed, create a copy of the original array using $copy = array_slice($array,0);
For the min value:
$min = min(array_map("array_pop",$array));
print_r($min);
For the key:
$min = array_keys(array_map("array_pop",$array), min(array_map("array_pop",$array)));
print_r($min[0]);

Best way to refer index which contains in array

In php I'm willing to check the existence of indexes that match with another values in array.
$indexes = array("index", "id", "view");
$fields = array(
"index" => 5,
"id" => 7,
"form" => 10,
"date" => 10,
);
MY ideal result is, in this case, to get "form" and "date". Any idea?
Try
$fields_keys = array_keys($fields);
$fields_unique = array_diff($fields_keys, $indexes);
The result will be an array of all keys in $fields that are not in $indexes.
You can try this.
<?php
$indexes = array("index", "id", "view");
$fields = array(
"index" => 5,
"id" => 7,
"form" => 10,
"date" => 10,
);
$b = array_diff(array_keys($fields), $indexes);
print_r($b);
You can use array_keys function to retrieve keys of a array
Eg:
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
Outputs
Array
(
[0] => 0
[1] => color
)
PHP Documentation
Your question is a little unclear but I think this is what you're going for
array_keys(array_diff_key($fields, array_fill_keys($indexes, null)));
#=> Array( 0=>"form", 1=>"date" )
See it work here on tehplayground.com
array_keys(A) returns the keys of array A as a numerically-indexed array.
array_fill_keys(A, value) populates a new array using array A as keys and sets each key to value
array_diff_key(A,B) returns an array of keys from array A that do not exist in array B.
Edit turns on my answer got more complicated as I understood the original question more. There are better answers on this page, but I still think this is an interesting solution.
There is probably a slicker way than this but it will get you started:
foreach(array_keys($fields) as $field) {
if(!in_array($field, $indexes)) {
$missing[] = $field;
}
}
Now you will have an array that holds form and date.

php multidimensional array

I want to create a twodimensional array in php. What is the correct syntax of creating an empty multidimensional array in php.
Secondly I want to create 7 two dimensional array in for
Take a look at the PHP online manual. The first example shows you how to create a multi dimensional array.
http://php.net/manual/en/function.array.php
<?php
$twoDimensionalArray = array (
"fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
?>
To do what you want in a for loop, you can do so like this
// the following creates a 2d array. the first dimension contains 7 arrays of numbers 1 to 10
$firstDimension = array();
for ($i = 0; $i < 7; $i++) {
$firstDimension[] = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
}
Unlike some other langauges (such as standard C), arrays in PHP are "sparse" (i.e.: they only take up the space they need) so you can define a multi-dimensional array simply via:
$testArray = array();
(i.e.: You don't need to reserve the amount of space you're going to require.) However, more usefully, you can add values as follow:
$testArray = array();
$testArray[0][0] = "Hello";
$testArray[0][1] = "World";
...
That said, I'd recommend reading the PHP array manual page, as you might want to use named indexes, etc. and it has better examples.
Multi-dimentional arrays are like regular arrays but the value to some (or all) or their keys are arrays.
For example you can create a two dimentional array like this:
$arr = array();
$arr[1] = array(1 => 'one', 2 => 'two');
And you can use it like this:
echo $arr[1][1]; //which prints "one"
To create empty multidimensional array in PHP, you can do the following.
$arr_1 = array();
Yes. That's all. You can insert any type of data or array in it. There is no specific declaration of various arrays in PHP.
Now, suppose I want to insert data inside this multidimensional array $arr_1. I need to create an array of addresses. Each address item will have city, state and country.
You can do this as follows:
$arr_1[0] = array(
'city' => 'Gurgaon',
'state' => 'Haryana',
'country' => 'India'
);
$arr_1[1] = array(
'city' => 'Los Angeles',
'state' => 'California',
'country' => 'United States'
);
$arr_1[1] = array(
'city' => 'Melbourne',
'state' => 'Victoria',
'country' => 'Australia'
);
You can create as many arrays as you want in this way.
If you want to learn more about PHP arrays (Indexed, Associative, Multidimensional), visit PHP arrays explained with examples - Webolute Blog
<?php
$twoDimensionalArray = array (
"fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
?>

Categories