I have this array where i need to get the biggest value but the biggest key
Array = [
0 = 2,
1 = 2,
2 = 1,
3 = 1,
],
the biggest value from array above are 2, but there's 2 keys where it has values of 2 which is 0 and 1. somehow i need to get the key of array where it's biggest one so the key are 1. and i just can't reorder the value since it'll mess up the key value because i'm gonna need the key
All you need is a loop that progresses through the array, along with two variables that you update appropriately as needed:
maxValue: The largest value seen so far
maxKey: The key for the largest value seen so far
During the loop, check the current element's key and value against these. If the value matches maxValue but the key is greater, update maxKey. If the value is greater than maxValue, change BOTH maxKey and maxValue to match the current element's key and value.
One approach would be to first filter the associative array, retaining only entries whose values are coincident with the highest value. Then, take the max value of array_keys() of that subarray to find the highest key.
$array = Array
(
0 => 2,
1 => 2,
2 => 1,
3 => 1
);
$array_max = array_filter($array, function($elem) USE ($array) {
return $elem == max($array);
});
echo max(array_keys($array_max));
hope this help you , first will get highest value with max($array) then will get max key
$array = array('2','2','1','1');
$highest_num = max($array);
$highest_key = max(array_keys($array,$highest_num));
print_r($highest_key);
Related
Let's say the following is true:
I have an associative array containing an unknown number of elements.
The keys are integers, starting at 1, and each is one more than the last.
There is an element with key N whose value is 1.
The value of each element with a key less than N is 0.
The value of each element with a key greater than N is 1.
This is the array:
The question is :
What is the fastest/smartest way to find the position of the first '1' in the array?
If you truly don't know the length of the array (a very odd situation), then probably all you can do is grow your search geometrically, i.e. skip 4, skip 8, skip 16, etc. until you find a 1, then cut back with a (geometric) binary search.
array_search is your best bet
// Make up some data...
$data = [];
for ($i = 1; $i <= 20; ++$i) {
$data[$i] = rand(0,5);
}
var_dump($data);
// Find the first one...
echo 'The first 1 is at position: ' . array_search(1, $data);
http://php.net/manual/en/function.array-search.php
I structured the item information in an unorthodox way, it is stored in three different arrays and are related by the key. I am looking to Sum the Quantities by ItemID.
1. Array #1 ItemID
$_SESSION["item_id"][]
1 => 1, 2 => 1, 3 =>2
2. Array #2 Size
$_SESSION["size"][]
1 => S, 2 => L, 3 =>S
3. Array #3 Quantity
$_SESSION["count"][]
1 => 250, 2 =>750, 3=>250
The result should be as follows:
ItemID # 1 --> Quantity 1000
ItemID # 2 --> Quantity 250
Could someone could help me with a function ?
Let's say, you have the following array in $_SESSION:
$_SESSION['item_id'] = array(1, 1, 2);
$_SESSION['size'] = array('S', 'L', 'S');
$_SESSION['count'] = array(250, 750, 250);
NOTE: the following answer take assumption that array length in those 3 SESSION value are equal.
You will need to create new array to store the result:
$newArrayResult = array();
After that, you will need to do for...each loop to extract currently accessed key:
foreach($_SESSION['item_id'] as $key => $value){
//the logic goes here
}
Next, we will use item_id as our array key in $newArrayResult. To do that, we will need to check first, if it is already defined. If not, create the key with default value 0. We do the checking by using built in function called array_key_exists. This way, we will avoid running into undefined key index error.
if(!array_key_exists($value, $newArrayResult)){
$newArrayResult[$value] = 0;
}
After we have the key for $newArrayResult, next step would be to simply store count value into it:
$newArrayResult[$value] += $_SESSION['count'][$key];
Done. Print the result to test:
print_r($newArrayResult);
Here is the whole code again, for you to copy-paste. Don't forget to read and understand the above flow first:
$_SESSION['item_id'] = array(1, 1, 2);
$_SESSION['size'] = array('S', 'L', 'S');
$_SESSION['count'] = array(250, 750, 250);
$newArrayResult = array();
foreach($_SESSION['item_id'] as $key => $value){
if(!array_key_exists($value, $newArrayResult)){
$newArrayResult[$value] = 0;
}
$newArrayResult[$value] += $_SESSION['count'][$key];
}
print_r($newArrayResult);
In PHP, max() returns the highest value in an array or the greatest value among inputs. If we have two or more equally greatest values, how to deal with that situation?
eg
$arr = array("a"=>1,"b"=>10, "c"=>10);
now, what should max($arr), return. Ideally it returns the first encountered highest value, b. What if I want both b and c as result?
If you have the highest value in that array (that is, what max() returns), you can just search for all occurrences of that value in the array:
$arrOfKeys = array_keys($arr, max($arr));
max() returns the maximum value, not the array key it is associated with. It will simply return (int) 10 in the example you give.
If you want a list of the keys that have the maximum value you could do something like this:
$max = max($array);
$maxKeys = array();
foreach ($array as $key => $val) {
if ($val == $max) {
$maxKeys[] = $key;
}
}
print_r($maxKeys);
/*
Array
(
[0] => b
[1] => c
)
*/
I have an array with a key and 3 values (day, start_time, end_time). I want to keep adding certain entries into this array while making sure each entry is unique. That means that every time I try to add an item into the array, I want to make sure it does not already exist in it. If it does exist, I want to be able to find the key that indicates that entry.
For example, this is the pre-existing array:
$array [0][0] = Monday
$array [0][1] = 2
$array [0][2] = 4
$array [1][0] = Tuesday
$array [1][1] = 3
$array [1][2] = 5
If I try to insert (Wednesday, 3, 5), then it should make the entry in the index 2.
If I try to insert (Monday, 2, 4), I need to be able to know that it is already in there and is indexed by 0.
How do I go about doing this?
I agree with the other answers here — it might be better to restructure your array so that there is no need to worry about duplication at all.
If you want to keep your current structure, however: use array_search.
$array = ...
$unique_check = array_search(array('Monday', 2, 4), $array);
if ( $unique_check === false )
// add to array
else
// $unique_check = the array key at which the existing matching element is located
Why not organize the array this way?
$array [Monday][0] = 2
$array [Monday][1] = 4
$array [Tuesday][0] = 3
$array [Tuesday][1] = 5
I have an array like this:
array[0] = "hello0"
array[1] = "hello1"
array[2] = "hello2"
Now I want to get the last key '2' of the array. I cant use end() because that will return the value 'hello2'.
What function should I use?
end() not only returns the value of the last element but also sets the internal pointer to the last element. And key() returns the key of the element this internal pointer currently ...err... points to.
$a = array(1=>'a', 5=>'b', 99=>'d');
end($a);
echo key($a);
prints 99
If the keys are not continuous (i.e. if you had keys 1, 5, 7, for example):
$highest_key = rsort(array_keys($myarray))[0];
If they are continuous, just use count($myarray)-1.
count($array) - 1
Won't work if you've added non-numeric keys or non-sequential keys.