Here is my array how can i find the minimum and maximum value. i.e,
output must be min=0;max=15
Array
(
[0] => 5-10
[1] => 10-15
[2] => 0-2
[3] => 15
)
<?php
$price_range=array("0-2","2-5","5-10","10-15","15");
foreach($price_range as $key=>$value){
$a=explode('-',$value);
if($a[0] != ''){$b[]= $a[0];}
if($a[1] != ''){$b[]= $a[1];}
}
echo 'min: '.$min=min($b);
echo 'max: '.$max=max($b);
?>
Use the PHP max() and min() functions on the array, assuming it already evaluates the values before setting them in the array.
Iterate through the array and check indexes OR use min()/max() function from php
Looks like a prime candidate for using array_reduce()
$price_range = ["0-2","2-5","5-10","10-15","15"];
$min = array_reduce(
$price_range,
function ($carry, $value) {
return min(array_merge(explode('-',$value), [$carry]));
},
PHP_INT_MAX
);
$max = array_reduce(
$price_range,
function ($carry, $value) {
return max(array_merge(explode('-',$value), [$carry]));
},
-PHP_INT_MAX
);
echo 'min: '.$min, PHP_EOL;
echo 'max: '.$max, PHP_EOL;
Try This...
$price=array();
$price_range=array("0-2","2-5","5-10","10-15","15");
foreach($price_range as $key=>$value){
$a=explode('-',$value);
array_push($price,$a[0]);
}
echo 'min: '.$min=min($price);
echo 'max: '.$max=max($price);
$input_range = ['0-2','2-5','5-10','10-15','15'];
$collect = [];
foreach($input_range as $range)
{
$collect = array_merge($collect, explode('-', $range));
}
$min = min($collect);
$max = max($collect);
You can simply make an use of array_walk along with the min and max function as
$price_range = array("0-2","2-5","5-10","10-15","15");
$result = array();
array_walk($price_range,function($v,$k)use(&$result){
$result = array_merge($result,explode('-', $v));
});
echo "Min value = ".min($result)." & Max value = ".max($result);
Related
I have a PHP array that is filled like so:
[
{"soldPrice":"228.96","dateSold":"05\/22\/2020"},
{"soldPrice":"204.99","dateSold":"06\/22\/2020"},
{"soldPrice":"399.99","dateSold":"08\/12\/2020"},
{"soldPrice":"350.00","dateSold":"08\/23\/2020"}
]
I was able to find the max by doing max($arr);, but now I added the dateSold. How can I find the min/max of this array, but also get the date that it sold?
It would echo 06/22/2020: 204.99 for min.
It would echo 08/22/2020: 399.99 for max.
I tried to add a function like this just to get the max.
function max_attribute_in_array($data_points, $value='soldPrice'){
$max=0;
foreach($data_points as $point){
if($max < (float)$point->{$value}){
$max = $point->{$value};
}
}
return $max;
}
$max = max_attribute_in_array($mainResponse);
var_dump($max);
but this was a no go.
This just returned int(0)
This gives you the complete entry of the array that has the maximum value:
function max_attribute_in_array($data_points, $value='soldPrice') {
$col = array_column($data_points, $value);
return $data_points[array_search(max($col), $col)];
}
From your example (which possibly has a typo since there's no 08/22/2020 date), it looks like you want the max of a key from the arrays which are within the overall array (in JS you'd say an array of objects).. which you've almost solved:
<?php
$data=[
["soldPrice"=>228.96,"dateSold"=>"05/22/2020"],
["soldPrice"=>204.99,"dateSold"=>"06/22/2020"],
["soldPrice"=>399.99,"dateSold"=>"08/12/2020"],
["soldPrice"=>350.00,"dateSold"=>"08/23/2020"]];
function max_attribute_in_array($arr, $key) {
$max=null;
foreach ($arr as $row) {
if ($row[$key]>$max) {
$max=$row[$key];
}
}
return $max;
}
function min_attribute_in_array($arr, $key) {
$min=count($arr)>0 ? $arr[0][$key] : null;
foreach ($arr as $row) {
if ($row[$key]<$min) {
$min=$row[$key];
}
}
return $min;
}
$maxSoldPrice=max_attribute_in_array($data, 'soldPrice');
$maxDateSold=max_attribute_in_array($data, 'dateSold');
echo $maxSoldPrice.", ".$maxDateSold."\n";
$keys=['soldPrice','dateSold'];
$mins=[];
foreach ($keys as $key)
$mins[$key]=min_attribute_in_array($data,$key);
print_r($mins);
Which should output
399.99, 08/23/2020
Array
(
[soldPrice] => 204.99
[dateSold] => 05/22/2020
)
I've switched the data to PHP arrays, what you've specified as the source looks like JSON, but you can convert JSON to PHP arrays using json_decode($json,true);. Note you could also iterate over the keys of each $row and build the max of each key that way (it would require some structural changes to max_attribute_in_array) - instead of having to specify each key. I've used an iteration approach for the min version just to demonstrate - you could use either (but probably best to be consistent)
Iterate with foreach over it and get min/max and remember the corresponding dates.
<?php
$data=[
["soldPrice"=>228.96,"dateSold"=>"05\/22\/2020"],
["soldPrice"=>204.99,"dateSold"=>"06\/22\/2020"],
["soldPrice"=>399.99,"dateSold"=>"08\/12\/2020"],
["soldPrice"=>350.00,"dateSold"=>"08\/23\/2020"]];
$min = INF;
$max = -INF;
foreach ($data as $elem) {
if ($elem['soldPrice'] > $max) {
$max = $elem['soldPrice'];
$maxDate = $elem['dateSold'];
} elseif ($elem['soldPrice'] < $min) {
$min = $elem['soldPrice'];
$minDate = $elem['dateSold'];
}
}
echo 'Max: ' . $max . ' => ' . $maxDate . '<br>';
echo 'Min: ' . $min . ' => ' . $minDate . '<br>';
This delivers:
Max: 399.99 => 08\/12\/2020
Min: 204.99 => 06\/22\/2020
I've created an array with 'maximum' values in.
$management = array(
'100' => '1',
'500' => '2',
'1000' => '3',
);
And created a loop to find the closest value, rounding it up.
$speed = 10;
$r= '';
sort($management);
foreach($management as $mgmt => $name) {
if($mgmt >= $speed) {
$r= $name;
}
}
$r= end($management);
So, where the $speed is 10, it should pick up the array key 100 and if it was 100 it should still pickup 100 but if the speed was 200, it would pickup 500
The above is picking up 500 when the $speed is 10 though.
Can anyone help please?
You have a couple of problems with your code. Firstly, the call to sort rewrites all the keys of the $management array which you are using for the comparison; you need to use ksort instead to sort by the keys instead of the values. Secondly, since the keys are in ascending order, once one is greater than the $speed value, they all will be, so you need to break from the loop once you find a higher value. Try this instead:
$r= '';
ksort($management);
foreach($management as $mgmt => $name) {
if($mgmt >= $speed) {
$r= $name;
break;
}
}
echo $r;
Demo on 3v4l.org
this is an example on how you can do it :
$array = array(1, 10, 100, 200, 400, 500, 1000);
public function getArrayRoundUp($array, $number) {
sort($array);
foreach ($array as $a) {
if ($a >= $number) return $a;
}
return end($array);
}
$value = 950;
$nearest = getArrayRoundUp($array, $value);
//the expect result will be 1000
echo $nearest;
Use the following function
function find(array $array, $search)
{
$last = null; // return value if $array array is empty
foreach ($array as $key => $value) {
if ($key >= $search) {
return $key; // found it, return quickly
}
$last = $key; // keep the last key thus far
}
return $last;
}
Tested and Working:-
echo find($management, 100); // Will result 100
echo find($management, 200); //Will result 500
$data = array
(
array("Ravi","Kuwait",350),
array("Sameer","UK",400),
array("Aditi","Switzerland",50),
array("Akshay","India",250),
array("rishi","Singapore",200),
array("Mukul","Ireland",100)
);
I want to put condition to the third row such that I can get entries of less than 300.
I suppose that you meant "the third element" in each nested array.Use array_filter function to get an array of elements, those third element's value is less than 300:
$result = array_filter($data, function($v) { return $v[2] < 300; });
print_r($result);
Try this code:
<?php
$data = array
(
array("Ravi","Kuwait",350),
array("Sameer","UK",400),
array("Aditi","Switzerland",50),
array("Akshay","India",250),
array("rishi","Singapore",200),
array("Mukul","Ireland",100)
);
$newArray = array();
foreach($data as $key => $value)
{
if($value[2] <= 100)
$newArray[] = $value;
}
print_r($newArray);
?>
You can achieve this using the PHP function array_filter() :
PHP
function limitArray($array) {
return ($array[2] <= 300);
}
print_r(array_filter($data, 'limitArray'));
evalIN
I am trying to manually sort a PHP array without making use of ksort.
This is how my code looks at the moment:
function my_ksort(&$arg){
foreach($arg as $key1 => $value1){
foreach($arg as $key2 => $value2){
if($key1 > $key2){
$aux = $value2;
$arg[$key2] = $value1;
$arg[$key1] = $aux;
}
}
}
}
It doesn't sort, I can't figure out how to make it sort.
You could try this:
function my_ksort(&$arg)
{
$keys=array_keys($arg);
sort($keys);
foreach($keys as $key)
{
$val=$arg[$key];
unset($arg[$key]);
$arg[$key]=$val;
}
}
I'm sorting the keys separately and then deleting the elements one-by-one and appending them to the end, in ascending order.
I'm using another sorting function (sort()), but if you want to eliminate all available sorting functions from your emulation, sort() is much easier to emulate. In fact, #crypticous's algorithm does just that!
This function return array in ASC. Take in consideration that I'm using goto which is supported in (PHP 5 >= 5.3.0)
function ascending_array($array){
if (!is_array($array)){
$array = explode(",", $array);
}
$new = array();
$flag = true;
iter:
$array = array_values($array); // recount array values with new offsets
(isset($min["max"])) ? $min["value"] = $min["max"] : $min["value"] = $array[0];
$min["offset"] = 0;
for ($i=0;$i<count($array);$i++){
if ($array[$i] < $min["value"]){ // redefine min values each time if statement executed
$min["value"] = $array[$i];
$min["offset"] = $i;
}
if ($flag){ // execute only first time
if ($array[$i] > $min["value"]){ // define max value from array
$min["max"] = $array[$i];
}
$flag = false;
}
if ($i === (count($array)-1)){ // last array element
array_push($new,$min["value"]);
unset($array[$min["offset"]]);
}
}
if (count($array)!=0){
goto iter;
}
print_r($new);
}
$arr = array(50,25,98,45);
ascending_array($arr); // 25 45 50 98
PS. When I was studying php, I wrote this function and now remembered that I had it (that's why I really don't remember what I am doing in it, though fact is it's working properly and hopefully there are comments too), hope you'll enjoy :)
DEMO
I was checking some issue related to this post and i wanted to give my insight about it ! here's what i would have done to implement php's sort :
$array_res = array();
$array = array(50,25,98,45);
$i=0;
$temp = $array[0];
$key = array_search($temp, $array);
while ($i<count($array)-1){
$temp = $array[0];
for($n=0;$n<count($array) ;$n++)
{
if($array[$n]< $temp && $array[$n] != -1 )
{
$temp = $array[$n];
}
else{continue;}
}
//get the index for later deletion
$key = array_search($temp, $array);
array_push($array_res, $temp);
/// flag on those which were ordered
$array[$key] =-1;
$i++;
}
// lastly append the highest number
for($n=0;$n<count($array) ;$n++)
{
if ($array[$n] != -1)
array_push($array_res, $array[$n]);
}
// display the results
print_r($array_res);
This code will display : Array
(
[0] => 25
[1] => 45
[2] => 50
[3] => 98
)
Short and sweet
function custom_ksort($arg)
{
$keys = array_keys($arg);
sort($keys);
foreach($keys as $newV)
{
$newArr[$newV] = $arg[$newV];
}
return $newArr;
}
It looks like your issue is that you're changing "temporary" characters $key1 and $key2 but not the actual arrays. You have to change $arg, not just $key1 and $key2.
Try something like:
$arr = Array(3=>"a",7=>"b");
print_r( $arr );
foreach( $arr as $k=>$v ){
unset($arr[$k]);
$arr[$k+1] = $v;
}
print_r($arr);
Is there an equivalent min() for the keys in an array?
Given the array:
$arr = array(300 => 'foo', 200 => 'bar');
How can I return the minimum key (200)?
Here's one approach, but I have to imagine there's an easier way.
function minKey($arr) {
$minKey = key($arr);
foreach ($arr as $k => $v) {
if ($k < $minKey) $minKey = $k;
}
return $minKey;
}
$arr = array(300 => 'foo', 200 => 'bar');
echo minKey($arr); // 200
Try this:
echo min(array_keys($arr));
Try with
echo min(array_keys($arr));
min() is a php function that will return the lowest value of a set. array_keys() is a function that will return all keys of an array. Combine them to obtain what you want.
If you want to learn more about this two functions, please take a look to min() php guide and array_keys() php guide
use array_search() php function.
array_search(min($arr), $arr);
above code will print 200 when you echo it.
For echoing the value of lowest key use below code,
echo $arr[array_search(min($arr), $arr)];
Live Demo
This also would be helpful for others,
<?php
//$arr = array(300 => 'foo', 200 => 'bar');
$arr = array("0"=>array('price'=>100),"1"=>array('price'=>50));
//here price = column name
echo minOfKey($arr, 'price');
function minOfKey($array, $key) {
if (!is_array($array) || count($array) == 0) return false;
$min = $array[0][$key];
foreach($array as $a) {
if($a[$key] < $min) {
$min = $a[$key];
}
}
return $min;
}
?>
$arr = array(
300 => 'foo', 200 => 'bar'
);
$arr2=array_search($arr , min($arr ));
echo $arr2;