This question already has an answer here:
Find which int was minimum in PHP [closed]
(1 answer)
Closed 9 years ago.
I am trying to retrieve the smallest value from an array. Here is my code:
$postID = get_the_id();
$variationP = get_post_meta($postID, '_variations', TRUE);
print_r($variationP);
This outputs the following:
Array ( [0] => 1 [1] => 2 [2] => 3 )
I am then looping through the array like this:
foreach ($variationP as $price){
echo $price;
}
Which then outputs the results like this:
123
How do I go about returning only the smallest result? I need just 1 to be returned.
Just echo array: min() returns the numerically lowest of the parameter values or array.
echo min($variationP);
If you want algorithm (not using min), it's really easy:
$min = 0;
function minPrice($elements){
foreach ($elements as $price){
if($min > $price){
$min = $price;
}
}
return $min;
}
It's good solution when you compare more complex elements, for example models from orm.
Use PHP's min() function:
$array = Array ( [0] => 1 [1] => 2 [2] => 3 );
$minimum = min($array);
echo $minimum; // 1
You can use min() function to get the smallest number in an array.
$a = array(3, 1, 2);
echo min($a);
This code output:
1
use min() function to get minimum value.
Related
This question already has answers here:
Find highest value in multidimensional array [duplicate]
(9 answers)
Closed 5 years ago.
i need to get the the max or highest value in a multi dimensional array.
here is my array $array:
[pay] => Array
(
[0] => Array
(
[title] => Array
(
[name] => 'hi'
)
[payment] => Array
(
[amount] => 35
[currency] => USD
)
)
[1] => Array
(
[title] => Array
(
[name] => 'lol'
)
[payment] => Array
(
[amount] => 50
[currency] => USD
)
)
[2] => Array
(
[title] => Array
(
[name] => 'ok'
)
[payment] => Array
(
[amount] => 30
[currency] => USD
)
)
)
i need to get the max value for amount which is 50. how can i do that?
here is what i tried but it did not work:
$max = -9999999; //will hold max val
$found_item = null; //will hold item with max val;
foreach($array as $k=>$v)
{
if($v['Total']>$max)
{
$max = $v['Total'];
$found_item = $v;
}
}
Simple as this one-liner. Get the payment column data, then pull the amount data from that generated array, then get the max value. Done and done. (Sorry it took me so long -- I had to convert your posted array to a usable php array.)
Input:
$array=["pay" => [
["title"=>["name"=>'hi'],"payment"=>["amount"=>35,"currency"=>"USD"]],
["title"=>["name"=>'lol'],"payment"=>["amount"=>50,"currency"=>"USD"]],
["title"=>["name"=>'ok'],"payment"=>["amount"=>30,"currency"=>"USD"]]
]
];
Method #1 (Demo):
echo max(array_column(array_column($array["pay"],"payment"),"amount"));
Method #2 (Demo):
$max=0;
foreach($array["pay"] as $subarray){
if($max<$subarray["payment"]["amount"]){
$max=$subarray["payment"]["amount"];
}
}
echo $max;
Method #3 (Demo):
$payments=array_column($array["pay"],"payment"); // declare payments array
rsort($payments); // sort by amount DESC
echo $payments[0]["amount"]; // access the first amount value
Output:
50
The benefits to method #1 are: code brevity, no condition statements, no global variable declarations/overwriting, just straight to the max value. What's not to love!
If method #1 is too scary, you can go with my method #2 (which was first posted by aendeerei). I don't prefer it because it requires the extra steps of initializing the $max variable, performing a conditional check on each iteration, and overwriting the $max variable when appropriate. Actual performance on the foreach loop is going to depend on the size of your array, but the difference between the two methods is going to be unnoticable to humans.
Method 3 might be my new favorite because there are no conditionals and just two functions before it is accessed purely by keys. However, it does require the declaration of a partial copy of the input array which must be sorted. Anyhow, take your pick -- it's all the same outcome.
Use Usort and get the 1st index
$arr= array
(
array
(
'payment' => array
(
'amount' => 35,
'currency' => 'USD'
)
),
array
(
'payment' => array
(
'amount' => 50,
'currency' => 'USD'
)
),
array
(
'payment' => array
(
'amount' => 80,
'currency' => 'USD'
)
)
);
function sortAmount($x, $y) {
return $y['payment']['amount'] - $x['payment']['amount'];
}
usort($arr, 'sortAmount');
echo "<pre>";
$highest=$arr[0];
print_r($highest)
//for value only
$highest=$arr[0]['payment']['amount'];
Working fiddle
http://phpfiddle.org/main/code/p5hw-ivei
$max = 0;
foreach ($array['pay'] as $key => $item) {
$amount = $item['payment']['amount'];
if ($amount > $max) {
$max = $amount;
}
}
echo $max;
Shorthand:
$result = array_reduce($array['pay'], function($a, $b){
return $a ? ($a['payment']['amount'] > $b['payment']['amount'] ? $a : $b) : $b;
});
var_dump($result['payment']['amount']);
Try this hope this will be helpful. Here we are just using simple foreach to get it done.
Solution 1:
try this code snippet here
$max=0;
foreach($yourArray["pay"] as $value)
{
if($max<$value["payment"]["amount"])
{
$max=$value["payment"]["amount"];
}
}
echo $max;
Solution 2:
Just for testing purpose i have converted you array to json. Here we are using array_column two times to get the columns
Try this code snippet here
$internals=array_column($yourArray["pay"],"payment");//retrieving payments
$amounts=array_column($internals, "amount");//retrieving amounts
arsort($amounts);
print_r(array_values($amounts)[0]);
Consider this example with an array named pay. You can adapt this method for your own array. This code will work for an array of n elements. Here I consider 3 as the number of elements in the array named $pay. You can replace the max elements in the array in the place of 3 for controlling the loop control variable 'i'.
$big=$pay[0];
for($i=1; $i<3; $i++){
if($pay[i]>$big)
$big=$pay[i];
}
echo $big;
I hope this is what you are looking for. Ask for any clarification.
This question already has answers here:
php - Is it possible to count the number of keys in an array?
(4 answers)
Closed 6 years ago.
I am using laravel 5, I need count the keys available inside every array index suppose for array[0] it has 7 keys, now I need the last key and before last key to compare which's value is bigger. how I can do using loop,as far I have tried.
Please Note The inner keys are stored as object key=>value pair.
foreach ($regions as $regions_key => $regions_value) {
echo sizeof($regions_key)
}
Help is appreciated.
Wouldn't you just count it within your loop:
$total = 0;
foreach($data as $sub_array) {
$total += count($sub_array);
}
After the above iteration is done to find your counts, $total will hold your count.
Example/Demo
Try this:
$countArr = array();
foreach ($regions as $regions_key => $regions_value) {
$countArr[$regions_key] = count($regions[$regions_key]); // create array of length of sub array
}
echo max($countArr); // max — Find highest value
To count the number of keys in an array. Try
$arr = Array
(
0 => 'hello',
1 => 'there',
2 => null,
3 => null,
4 => 3,
);
var_dump(count($arr));
This question already has answers here:
Sort a flat, associative array by numeric values, then by non-numeric keys
(8 answers)
Closed 2 years ago.
I've been breaking my head over the following problem.
I've got this array:
[596] => 2
[9] => 2
[358] => 2
[1579] => 1
[156] => 1
[576] => 1
[535] => 1
As you can see, the values are ordered in a descending way, but the keys are random. I would like to keys to be sorted DESC as well though. I've been playing with array_multisort, but I haven't been able to fix the problem with it. The first problem that I encountered was the fact that array_multisort reindexes numeric keys. I changed to keys to a non-numeric variant, namely k596 etc... That made me able to sort the keys, but not like I wanted it to.
[k9] => 2
[k596] => 2
[k358] => 2
[k576] => 1
[k535] => 1
[k1579] => 1
[k156] => 1
The result that I would like to see in the end is:
[k596] => 2
[k358] => 2
[k9] => 2
[k1579] => 1
[k576] => 1
[k535] => 1
[k156] => 1
Is anyone able to help me out here? There must be a simple way to do this, right?
uksort($array, function ($a, $b) use ($array) {
if ($array[$a] != $array[$b]) {
return $array[$a] - $array[$b];
}
return $a - $b;
});
Insert appropriate comparison operations, using simply - here as an example. This is somewhat trickier if you're dependent on PHP < 5.3 and don't have anonymous functions.
Ok this question is a bit more tricky then I thought! Given an array $arry = array('a'=>'hilbert', 'b'=>'noether', 'c'=>'landau');
I would generate a second array containing tuples like this:
$brry = array();
foreach($arry as $key => $value){
$brry[] = array($key,$value);
}
//Now $brry looks like:
//$brry:
// [0] => array('a','hilbert');
// [1] => array('b','noether');
// [2] => array('c','landau');
//now you can easily sort it!
usort($brry, "cmp");
//And then transform it back to the array structure you have before
foreach($brry as $value){
$crry[$value[0]] = $value[1];
}
//with this sorting function cmp:
function cmp($first, $second){
if(strcmp($first[1], $second[1]) != 0){
return strcmp($first[1], $second[1]);
}
else{
return strcmp($first[0], $second[0]);
}
}
The function cmp sorts by strings now so strcmp("192","20") > 0 while this might not be true for integers!
I am creating a faceted search, and I'm am trying to use array_intersect to compare the arrays and find the inputs that match.
The problem is that I will have a variable amount of arrays at anytime depending on what filters the user has selected:
$array_1, $array_2, $array_3 etc...
How do I create an array_intersect function that is dynamic in this sense?
This is what I've tried:
$next_array = 0;
for($i = 0; $i < $array_count; $i++) {
$next_array++;
if ($i == 0) {
$full_array = ${array_.$i};
} else {
if(!empty(${cvp_array.$next_array})) {
$full_array = array_intersect($full_array, ${cvp_array_.$next_array});
}
}
}
------------- EDIT -------------
I'll try to narrow down my goal a bit more:
If the user clicks three filters, this results in three arrays being created with each having individual results:
Array_1 ( [0] => 2, [1] => 4, [2] => 6 )
Array_2 ( [0] => 1, [1] => 4, [2] => 6 )
Array_3 ( [0] => 6, [1] => 7, [2] => 8 )
I need code that will find the number that is in ALL of the arrays. And if there is no common number then it would end as false or something. In the case above, I'd need it to retrieve 6. If it was only the first two arrays, it would return 4 and 6.
Try this:
$fullArray = array($array1, $array2, $array3...);
call_user_func_array('array_intersect', $fullArray);
One can use:
$intersect = array_intersect(...$fullArray);
First of all, turn those arrays into an array of arrays. Then you can use array_reduce combined with array_intersect to reduce a variable amount of arrays down to one.
You can turn those array to a single array named $total_array by using array_combine(),
then use array_intersect($full_array, $total_array). I hope this useful
This question already has answers here:
Get min and max value in PHP Array
(9 answers)
Closed 7 months ago.
I'm trying to select the maximum value for a particular key in a multidimensional array. I'm having trouble "getting to" the key in question...
So, the array (which is much more lengthy than what I'm posting here)
[0] => stdClass Object
(
[id] => 70
[cust] => 4
[dnum] => 1
[upper] => Array
(
[0] => 66
)
)
[1] => stdClass Object
(
[id] => 43
[cust] => 42
[dnum] => 2
[upper] => Array
(
[0] => 77
)
)
[2] => stdClass Object
(
[id] => 12
[cust] => 3
[dnum] => 0
[upper] => Array
(
[0] => 99
)
)
I'm trying to find the maximum "dnum" value across the entire array, so in this example, $max = 2. I know that the max function allows me to do this, but I'm not sure how to reference the dnum element without putting the whole thing in a foreach loop, and if I do that, then max wouldn't be the function to use, right?
So, I can't exactly do this:
$max = max($myarray[]->dnum);
Is there a way for me to do this without having to recreate the entire array?
In PHP 5.2 the only way to do this is to loop through the array.
$max = null;
foreach ($arr as $item) {
$max = $max === null ? $item->dnum : max($max, $item->dnum);
}
Note: I've seeded the result with 0 because if all the dnum values are negative then the now accepted solution will produce an incorrect result. You need to seed the max with something sensible.
Alternatively you could use array_reduce():
$max = array_reduce($arr, 'max_dnum', -9999999);
function max_denum($v, $w) {
return max($v, $w->dnum);
}
In PHP 5.3+ you can use an anonymous function:
$max = array_reduce($arr, function($v, $w) {
return max($v, $w->dnum);
}, -9999999);
You can use array_map() too:
function get_dnum($a) {
return $a->dnum;
}
$max = max(array_map('get_dnum', $arr));
$max = 0;
foreach($array as $obj)
{
if($obj->dnum > $max)
{
$max = $obj->dnum;
}
}
That function would work correctly if your highest number is not negative (negatives, empty arrays, and 0s will return the max as 0).
Because you are using an object, which can have custom properties/structures, I don't believe there are really any 'predefined' functions you can use to get it. Might as well just use a foreach loop.
You really can't get away from a foreach loop, as even internal functions use a foreach loop, it is just behind the scenes.
Another solution is
$numbers = array();
foreach($array as $obj)
{
$numbers[] = $obj->dnum;
}
$max = max($numbers);
The simplest way is probably your initial thought, which is to loop your array once, and pull out all the dnum keys into a separate array, then call max() on that:
$out = array();
foreach($myarray as $obj) {
$out[] = $obj->dnum;
}
echo max($out);
You could do it without creating a separate array, but you'll end up calling max() a lot more often. Performance/memory usage will be different between the two, you could always benchmark it:
$first = $myarray[0]; //assume zero start index
$max = $first->dnum;
foreach($myarray as $obj) {
$max = max($max,$obj->dnum);
}
echo $max;
The only other way you could go about it would be to sort your array using usort() and a custom sorting function based on the object dnum properties. This is probably going to be much slower than just looping your array however, so I don't think I'd recommend it unless you needed the array sorted as a side effect.
If you like oneliners
$max = max( array_map(function( $row ){ return $row->dnum; }, $myarray) );
For anyone still interested, try this...
$min = min(array_column($myarray, 'dnum'));
$max = max(array_column($myarray, 'dnum'));