I have this loop and im wondering how can i get the MIN and MAX value inside the loop:
foreach($result_1 as $key_1) {
if($key_1->ordering > $key_0->ordering ) {
echo $key_1->ordering;
}
}
RESULT : 234
RESULT WANTED IS MIN (2) AND MAX (4) VALUES
Sounds like a good job for the functional reduce approach. You can do this in PHP with the array_reduce function:
You pass in an array, a callback and a starting value and the function will call the callback with the current value and the next item from the array and store the result.
php> $array = [ 6, 2, 8, 4 ];
array (
0 => 6,
1 => 2,
2 => 8,
3 => 4,
)
php> array_reduce($array, 'min', reset($array));
int(2)
php> array_reduce($array, 'max', reset($array));
int(8)
In this example I used min and max respectively as the callback and the first array item as the starting value.
In order to use this properly on your array you can pass in a custom callback using an anonymous function:
function ($a, $b) {
return max($a->ordering, $b->ordering);
}
You just need to loop through the array once and check every value against the current minimum/maximum, and replace it if it is smaller/bigger.
$min = reset( $array )->ordering; // Assign any value to start (just the first in this case)
$max = reset( $array )->ordering; // Assign any value to start (just the first in this case)
foreach ( $array as $object ) {
//max
if( $object->ordering > $max ) {
$max = $object->ordering;
}
//min
if( $object->ordering < $min ) {
$min = $object->ordering;
}
}
echo $min;
echo $max;
Just use the min($result_1) and max($result_1) functions that are built into PHP.
http://us2.php.net/max
http://us2.php.net/min
Edit:
Since it's an array of objects, try using two temporary variables to keep track of the min and max. I'm assuming in this code you're looking for the max and min ordering.
$min = 1000000;
$max = -1000000;
foreach($result_1 as $key_1) {
if($key_1->ordering > $max ) {
$max = $key_1->ordering;
}
else if($key_1->ordering < $min) {
$min = $key_1->ordering;
}
}
echo $min;
echo $max;
You can take the logic of a selection sort and use it to find the minimum value. I'm sure you can figure out from this code how to find the max.
$min = 0;
foreach($result_1 as $key_1) {
$min = $key_1->ordering
foreach($result_1 as $key_2) {
if($min > $key_2->ordering) {
$min = $key_2->ordering;
}
}
}
Here is my test:
$data = array(
5,
6,
7,
1,
9,
11,
3
);
$min = 0;
foreach($data as $key => $value) {
$min = $value;
foreach($data as $key2 => $value2) {
if($min > $value2) {
$min = $value2;
}
}
}
echo $min . "\n"; // 1
Related
I have multidimensional array and me need to get a minimum value.
Array may be [65,4,4,511,5,[[54,54[.[.[..].].]] and so on.
example code
<?php
$arr = [5, 1 , 2, 3, [1,5,59,47,58,[0,12,562]]];
function NumMin($arr)
{
$num = '';
foreach ($arr as $item => $i) {
if(is_array($i)){
NumMin($i);
}
else{
$num .= $i.',';
}
}
$num .= $num;
return $num;
}
$g = NumMin($arr);
var_dump($g);
I need to get 0
You can use array_walk_recursive() function to flatten a given array (makes it one-dimensional).
And use simply min() function for getting the desired output after.
array_walk_recursive($arr, function($v) use (&$res){
$res[]=$v;
});
echo min($res);
Demo
<?php
$GLOBALS["min"] = 999999; //min value int
$arr = [[[5,6],7],9,7,5, 1 , 2, 3, [1,5,59,47,58,[1,12,562]]];
array_walk_recursive($arr, 'NumMin');
function NumMin($item)
{
if(intval($item) <= intval($GLOBALS["min"]))
{
$GLOBALS["min"] = intval($item);
}
}
// The end, $GLOBALS["min"] will have the least value
echo $GLOBALS["min"];
?>
How to find max value from array when there is integer,string and special symbol in array without using inbuilt function in php ?
is_numeric is the PHP Built in method. If you don't want to use that then we have to type cast using (int) and check.
$arr = [1, 3, -10, 'string', true, [23]];
$max = null;
foreach($arr as $key => $val) {
if (is_numeric($val)) {
if ($max == null) {
$max = $val;
} else if ($val > $max) {
$max = $val;
}
}
}
Try to use this:
$maxs = array_keys($array, max($array));
Using this code you can find max value from an array:
$array = array('a','b',1,2,'$','^');
$max = $temp = 0;
//This loop is to get max value from array
for ($i = 0 ; $i < count($array); $i++) {
if ($i == 0) {
$max = $temp = $array[$i];
}
if ($i > 0) {
if ($array[$i] > $temp) {
$max = $array[$i];
}
}
}
print_r($max);
Since you can't do math to a string or Boolean value you could try math and if that fails it's not numeric.
$arr = [1, "BBB", 23, -10, 'str', true, false, 50, "#", "$"];
$max = 0;
Foreach ($arr as $v){
If(!#$v/1==0 && $v>$max) $max =$v;
}
Echo $max;
https://3v4l.org/Po31i
If you try "str"/1 you will get the result 0 and an error notice.
The # suppress the error.
Edit, forgot special symbol in array
I would like to find the second highest variable in an array.
For example if I have:
$cookies = array(
"chocolate" => "20",
"vanilla" => "14",
"strawberry" => "18",
"raspberry" => "19",
"bluebery" => "29"
);
I can use max($cookies) to find the highest variable, which is "bluebery" => "29".
But how do I find the second highest? "chocolate" => "20"
Sort it and get the second item is the easiest way:
arsort($cookies);
$keys = array_keys($cookies);
echo $keys[1]; // chocolate
echo $cookies[$keys[1]]; // 20
If you want a more efficient way, you can also do it manually, by keeping track of both the highest and second-highest items at the same time:
function secondMax($arr) {
$max = $second = 0;
$maxKey = $secondKey = null;
foreach($arr as $key => $value) {
if($value > $max) {
$second = $max;
$secondKey = $maxKey;
$max = $value;
$maxKey = $key;
} elseif($value > $second) {
$second = $value;
$secondKey = $key;
}
}
return array($secondKey, $second);
}
Usage:
$second = secondMax($cookies);
echo "{$second[0]} => {$second[1]}"; // chocolate => 20
For fun you could use max() twice :)
For example:
Duplicate the array
Run max()
Remove the max
Run max() again
The alternative would to sort the array based on values and get the second element of the array. I'd be curious which is faster. Likely the sort.
arsort($cookies) AND array_shift($cookies) AND list($k, $v) = each($cookies);
echo "$k => $v"; // chocolate => 20
rsort($cookies);
echo $cookies[1];
Try :
asort($cookies);
end($cookies);
prev($cookies);
list($key,$value) = each($cookies);
or reverse it
arsort($cookies);
reset($cookies);
next($cookies);
list($key,$value) = each($cookies);
** Edit **
I thought I'd share this anyway, if someone would stumble across this and need it :
/**
* Returns the key => value pair with the specific rank.
* if $rank is 0, falase is returned. If $rank is positive,
* then the $rank th smallest pair is returned. If $rank
* is negative, then the $rank th biggest pair is returned.
* If $rank range is outside the size of the array, false
* is returned. If a callable function is provided, it will
* be used to sort the data. If $keySort is true, then the
* data will be sorted by keys instead (the callback functions
* will receive the keys to compare instead of values)
*
* #param $data array
* #param $rank int
* #param $cmd_function callable (optional)
* #param $keySort boolean (optional)
* #return array the key => value pair or false
*/
function findByRank($data, $rank, $cmd_function = null, $keySort = false) {
if (($rank == 0) || (abs($rank) > count($data))) {
return false;
}
$sort = ($keySort?'k':'a').'sort';
if ($cmd_function != null) {
$sort = 'u'.$sort;
$sort($data, $cmd_function);
} else {
$sort($data);
}
if ($rank > 0) {
reset($data);
$next = 'next';
} else {
end($data);
$next = 'prev';
$rank = abs($rank);
}
while (--$rank > 0) $next($data);
return each($data);
}
$cookies = array(
"chocolate" => "20",
"vanilla" => "14",
"strawberry" => "18",
"raspberry" => "19",
"bluebery" => "29"
);
header('Content-type:text/plain; charset=utf-8');
var_dump(findByRank($cookies, -10)); // -> false
var_dump(findByRank($cookies, -2)); // -> 'chocolate' key=>value pair
var_dump(findByRank($cookies, -1)); // -> 'blueberry' key=>value pair
var_dump(findByRank($cookies, 0)); // -> false
var_dump(findByRank($cookies, 1)); // -> 'vanilla' key=>value pair
var_dump(findByRank($cookies, 3)); // -> 'raspberry' key=>value pair
Sort the array descending and take the second value. Or, to be save, take the first value and go through the array until you find a smaller one.
function second_largest($arr)
{
sort($arr, SORT_NUMERIC);
return($arr[count($arr) - 2]);
}
//echo 3
echo second_largest(array(0, 3, 4, 1, 2));
Check this URL
http://maheshbokkisam.blogspot.in/2013/04/find-nth-highest-value-in-array-without.html
Find Nth/ N th highest value from given array without using any sorting in PHP
$ar = array(23,56,87,12,98,85,24,54,99,100,1,4,5,2,76,37,92);
$n = count($ar) - 5;
for($i = 0; $i < $n; $i++){
// Get the max value from array // get the Nth value from last loop
echo $a = max($ar);
echo "<br /><pre>"; print_r($ar);
$ar = array_flip($ar); // Flip the array
//print_r($ar);
unset($ar[$a]); // Unset the max value from array
//print_r($ar);
$ar = array_flip($ar); // Flip the array
echo "</pre>";
echo "<hr />";
}
<?php
// Finding Second highest number (In case of index of array is random)
$arr = [-5 => 33, -4 => -2, 8 => 0, 44, 44, 44, 44, 44];
$max = -INF;
$secondMax = -INF;
$size = sizeof($arr);
if ($size > 1) {
foreach ($arr as $key => $value) {
echo "KEY-> ", $key, "VALUE->", $value, "\n";
if ($value > $max) {
$max = $value;
} else {
if ($value < $max && $value > $secondMax) {
$secondMax = $value;
}
}
}
} else if ($size == 0) {
$max = "No Max element";
$secondMax = "No Second highest element";
} else {
foreach ($arr as $key => $value) {
$max = $arr[$key];
$secondMax = "No second highest element";
}
}
echo "maxvalue = ", $max, "\n";
echo "secondmax =", $secondMax;
I am using the range() function to create an array. However, I want the keys to be the same as the value. This is ok when i do range(0, 10) as the index starts from 0, however if i do range(1, 11), the index will still start from 0, so it ends up 0=>1 when i want it to be 1=>1
How can I use range() to create an array where the key is the same as the value?
How about array_combine?
$b = array_combine(range(1,10), range(1,10));
Or you did it this way:
$b = array_slice(range(0,10), 1, NULL, TRUE);
Find the output here: http://codepad.org/gx9QH7ES
There is no out of the box solution for this. You will have to create the array yourself, like so:
$temp = array();
foreach(range(1, 11) as $n) {
$temp[$n] = $n;
}
But, more importantly, why do you need this? You can just use the value itself?
<?php
function createArray($start, $end){
$arr = array();
foreach(range($start, $end) as $number){
$arr[$number] = $number;
}
return $arr;
}
print_r(createArray(1, 10));
?>
See output here: http://codepad.org/Z4lFSyMy
<?php
$array = array();
foreach (range(1,11) as $r)
$array[$r] = $r;
print_r($array);
?>
Create a function to make this:
if (! function_exists('sequence_equal'))
{
function sequence_equal($low, $hight, $step = 1)
{
return array_combine($range = range($low, $hight, $step), $range);
}
}
Using:
print_r(sequence_equal(1, 10, 2));
Output:
array (
1 => 1,
3 => 3,
5 => 5,
7 => 7,
9 => 9,
)
In PHP 5.5 >= you can use Generator to make this:
function sequence_equal($low, $hight, $step = 1)
{
for ($i = $low; $i < $hight; $i += $step) {
yield $i => $i;
}
}
I have a 2D array in the format:
[
[1, 23, 20],
[2, 45, 30],
[4, 63, 40],
...
]
I am trying to search the array and return elements [0] and [1] from the row where element [1] is lowest. I have the following code to return the lowest value in [1] but I'm not sure how to get element [0] as well.
$min = PHP_INT_MAX;
foreach ($test as $i) {
$min = min($min, $i[1]);
}
In the above example I would return [1, 23]
Thanks,
You should use usort for this:
usort($test, function($a, $b) {
return $a[1] - $b[1];
});
$min = $test[0];
Note that this uses anonymous functions, which were introduced in PHP 5.3. In previous versions, you need to use named functions and pass the name as a string to usort.
You could use array_reduce:
$array = array(
array(1, 23, 20),
array(2, 45, 63),
array(4, 63, 40),
);
$callback = function ($a1, $a2) {
if ($a1[1] >= $a2[1]) {
return $a2;
} else {
return $a1;
}
}
$min = array_reduce($array, $callback, array(0, PHP_INT_MAX, 0));
var_dump($min); // array(1, 23, 20);
Now, this will likely have issues if you have multiple elements with identical [1] elements... But it transparently handles the case where the array is empty. And in general, all you need to do is do your comparison in the callback function for all "filtering" type problems where you can abstract the filtering to a comparison of 2 elements. So you do string comparison, etc to determine which of the 2 is better...
And it should be more efficient than a sort, since it only requires a single pass over the array (It's O(n) whereas sorting is O(n log n) and at worst O(n^2))...
This will do the job.
$min0 = PHP_INT_MAX;
$min1 = PHP_INT_MAX;
foreach ($test as $i) {
if($i[1] < $min1)
{
$min0 = $i[0];
$min1 = $i[1];
}
}
This will result in $min0 == 1 and $min1 == 23
You'll need to introduce some basic logic:
$result = array(0, PHP_INT_MAX);
foreach($test as $i)
if($i < $result[1])
$result = array($i[0], $i[1]);
You can use a simple min (O(n)) loop like you did, and array_slice to assign the first two indexes when a lowest is found :
$min = PHP_INT_MAX;
$arrMin = array();
foreach ($test as $i) {
if ($i[1] < $min) {
$min = $i[1];
$arrMin = array_slice($i, 0, 2);
}
}
you should just grab the array key of the smallest number:
$min = PHP_INT_MAX;
$minkey = 0;
foreach ($test as $key => $i) {
if($min > $i[1]) {
$min = $i[1];
$minkey = $key;
}
}
then, you can just access the whole thing with $test[$minkey]