If I have an average score of:
$average = 95.00000000
And I have an array:
$grades = array("91-100"=>"A+","80-89"=>"A","70-79"=>"B","60-69"=>"C","50-59"=>"D","0-49"=>"F");
When I try to get an average grade by doing:
$grade = $grades[$average];
I get an error:
Notice: Undefined index: 95.00000000
I think the issue comes from the the key's of the array, but is there a way to do what i'm trying to achieve?
You have to iterate over the keys, and check if your value is between them :
$grades = array("91-100"=>"A+","80-89"=>"A","70-79"=>"B","60-69"=>"C","50-59"=>"D","0-49"=>"F");
$average = 95.00000000 ;
$grade = '' ;
foreach ($grades as $val => $cur_grade) {
list($min, $max) = explode('-', $val); // split key into min and max
if ($average >= $min && $average <= $max) { // compare
$grade = $cur_grade ; // get the value
break ; // stop the loop
}
}
echo $grade ;
Will outputs :
A+
Note that if your $average is not in the range (ex. 69.9), it will match will no case. So you could use "90-100", "80-90", ...
$grades = array("90-100"=>"A+","80-90"=>"A","70-80"=>"B","60-70"=>"C","50-60"=>"D","0-50"=>"F");
$average = 69.9 ;
// ..code above..
echo $grade ; // Outputs "C"
And
$average = 70.0 ;
// ..code above..
echo $grade ; // Outputs "B"
I would suggest changing the grade array to a simpler structure, thus you would get a simpler and more predictable code
<?php
$average = 95.00000000;
$grades = array(
array(
'grade' => 'A+',
'max' => 100,
'min' => 90
),
array(
'grade' => 'A',
'max' => 89,
'min' => 80
),
array(
'grade' => 'B',
'max' => 79,
'min' => 70
),
array(
'grade' => 'C',
'max' => 69,
'min' => 60
),
array(
'grade' => 'D',
'max' => 59,
'min' => 50
),
array(
'grade' => 'F',
'max' => 49,
'min' => 0
),
);
$result = null;
$averageScore = (int) floor($average); // it's better to compare int to int instead of float to int
foreach($grades as $grade) {
if ($average < $grade['max'] && $average >= $grade['min']) {
$result = $grade['grade'];
break;
}
}
if ($result !== null) {
echo 'Your grade is: ' . $result;
} else {
echo 'Grading error, please ask your professor for details!';
}
Related
I'm pretty new to PHP and i'm stuck in the following scenario. I have an array with some values and I want to get the max value in the array set.
For ex:
$array = array(
0 => array(
'1' => '123',
'2' => '120',
'3' => '30',
'4' => '150'
),
1 => array(
'1' => '123',
'2' => '122',
'3' => '30',
'4' => '158'
),
2 => array(
'1' => '123',
'2' => '129',
'3' => '300',
'4' => '150'
)
);
The value i'm expecting is 300.
I have tried the following code and i don't know how to get the maximum value from all the sub arrays.
$max = 0;
foreach( $array as $k => $v ){
//this is where i need help
}
Any kind of help would be highly appreciated.
You can flatten your array first using array_merge(...$array), then just use the max() function:
$new_array = array_merge(...$array);
echo max($new_array);
Demo
I took #Hirumina's solution and just set $max = $y if $y was > $max
$max = 0;
foreach( $array as $k => $v ) {
foreach($v as $x => $y) {
if($y > $max){
$max = $y;
}
}
}
echo $max;
$new_array = array_map(function($value){
return max($value);
}, $array);
echo max($new_array);
Here array_map function will get max value from individual $array and store in $new_array.
Then max($new_array) will give you max value.
As you can see I have the thousands_sep with a dot, and "Summe" as the last column obv. is trying to calculate the sum of the rows but it uses 1556€ as 1.556€ thats why i get 234€ instead of 1.788
for ( $a = 0; $a < $i; $a++){
$sum += $tabledata[$a]['value'];
}
$ajaxreturn['beschriftungen'] = $beschriftungen;
$ajaxreturn['chartData'] = $chartdata;
$ajaxreturn['tablehead'] = $tablehead;
$tabledata[(count($tabledata))]= array('category'=>"Summe",'value' => number_format($sum, 0, ',', '.').'€', 'id' => $i);
I tried to change many things but what i need is that the input is "converted" to a number without the '.'
$chartdata[] = array('date' => $iddate, 'value' => round($zeile['summe']), 'id' => $i);
$tabledata[] = array('category' => $beschriftung, 'value' => number_format($zeile['summe'], 0, '', '.').'€', 'id' => $i);
Instead of trying to calculate the sum from the formatted number array ($tabledata), you should calculate the sum alongside the tabledata, like:
$beschriftungen[$iddate] = $beschriftung;
$chartdata[] = array('date' => $iddate, 'value' => round($zeile['summe']), 'id' => $i);
$tabledata[] = array('category' => $beschriftung, 'value' => number_format($zeile['summe'], 0, '', '.').'€', 'id' => $i);
$sum += $zeile['summe'];
Use str_replace('.', '', $value); or even better, preg_replace('/\D/', '', $value). preg_replace will remove also the currency symbol and possible spaces.
am trying to find out min x and min y values in whole array , i tried with min and max function but no success so far
i have xy values of board in 2d array
$xydata = array(
array('x' => 17.0, 'y' => 2.83),
array('x' => 20.83, 'y' => 65.37 ),
array('x' => 17.85,'y' => 3.57 ),
array('x' => 17.13, 'y' => 41.33 ),
array('x' => 24.27, 'y' => 53.48 ),
array('x' => 13.1, 'y' => 16.35),
array('x' => 13.1, 'y' => 66.855 )
);
i want to find corners of board
globally i have min x/y max x/y which i got through min() and max () functions
what i want is to get min y against min x
like if through $xydata i search with min x which is 13.1 i should get min y 16.35 because the other min x 13.1 y value is 66.855 is higher .... so any idea how it could be done
Sample code:
$xydata = array(
array('x' => 17.0, 'y' => 2.83),
array('x' => 20.83, 'y' => 65.37 ),
array('x' => 17.85,'y' => 3.57 ),
array('x' => 17.13, 'y' => 41.33 ),
array('x' => 24.27, 'y' => 53.48 ),
array('x' => 13.1, 'y' => 66.855 ),
array('x' => 13.1, 'y' => 16.35),
);
$min = $xydata[0];
foreach ($xydata as $d) {
if ($d['x'] < $min['x'] || ($d['x'] == $min['x'] && $d['y'] < $min['y'])) {
$min = $d;
}
}
echo'<pre>',print_r($min),'</pre>'; // TODO
Try this, best solution is use shorting of array
$xydata = array(
array('x' => 17.0, 'y' => 2.83),
array('x' => 20.83, 'y' => 65.37 ),
array('x' => 17.85,'y' => 3.57 ),
array('x' => 17.13, 'y' => 41.33 ),
array('x' => 24.27, 'y' => 53.48 ),
array('x' => 13.1, 'y' => 16.35),
array('x' => 13.1, 'y' => 66.855 )
);
$count = 0;
foreach ($xydata as $type) {
$count++;
}
$count--;
function sortByOrder($a, $b) {
return $a['x'] - $b['x'];
}
usort($xydata, 'sortByOrder');
echo "min of x => ".$xydata [0]['x'];
echo "max of x => ".$xydata [$count]['x'];
function sortByOrdery($a, $b) {
return $a['y'] - $b['y'];
}
usort($xydata, 'sortByOrdery');
echo "min of y => ".$xydata [0]['y'];
echo "max of y => ".$xydata [$count]['y'];
DEMO
You can try the below functions:
function array_max($a) {
foreach ($a as $value) {
if (is_array($value)) {
$value = array_max($value);
}
if (!(isset($max))) {
$max = $value;
} else {
$max = $value > $max ? $value : $max;
}
}
return $max;
}
function array_min($a) {
foreach ($a as $value) {
if (is_array($value)) {
$value = array_min($value);
}
if (!(isset($min))) {
$min = $value;
} else {
$min = $value < $min ? $value : $min;
}
}
return $min;
}
Its work fine for me :)
You can use array_multisort to build a function that will give you all possible pairs of min/max:
function getXY(array $xyArray, $x = 'min', $y = 'min')
{
$xFlag = $x === 'max' ? SORT_DESC : SORT_ASC;
$yFlag = $y === 'max' ? SORT_DESC : SORT_ASC;
array_multisort(
array_column($xyArray, 'x'), $xFlag,
array_column($xyArray, 'y'), $yFlag,
$xyArray
);
return array_shift($xyArray);
}
Here is working demo.
i have 7 numbers in random from -100 to 100, from those seven numbers i need to find the biggest diference between each them
example:
-50 , 60 , -4 , 80 , 25, -34, 15
the output will be 130 -50 and 80 is the biggest diference
but i need in php
i have tried echo max(rand(-100, 100));
but it is not the output im looking for
this i tried too:
$myarray = array(
'this' => 2,
'that' => 14,
'them' => -5,
'other' => 200,
'nothing' => 42,
'somethingelse' => 1,
'you' => 10,
'me' => 30);
foreach ($myarray as $key => $value) {
if (!isset ($min) || $value < $min) { $min = $value; }
if (!isset ($max) || $value > $max) { $max = $value; }
}
$diff = $max - $min;
echo $diff;
any suggestion?
<?php
$array = array(-50 , 60 , -4 , 80 , 25, -34, 15);
$min = 0;
$max = 0;
foreach($array as $element) {
if ($element < $min) $min = $element;
if ($element > $max) $max = $element;
}
echo $max - $min;
Your approach using max() wasn’t wrong, but max() expects an array as its first parameter whereas rand() only returns a single integer.
The solution should be:
$diff = max($myarray) - min($myarray);
try this one
$myarray = array(
'this' => 2,
'that' => 14,
'them' => -5,
'other' => 200,
'nothing' => 42,
'somethingelse' => 1,
'you' => 10,
'me' => 30);
function bigDiff($arr){
if(count($arr)>0){
$max = max($arr);
$min = min($arr);
$diff = ($max)-($min);
return $diff;
}
return "Null input array provided";
}
echo bigDiff($myarray);
outputs 205
This could be another way:
$arr = array(
'this' => 2,
'that' => 14,
'them' => -5,
'other' => 200,
'nothing' => 42,
'somethingelse' => 1,
'you' => 10,
'me' => 30
);
sort($arr);
$diff = $arr[count($arr) - 1] - $arr[0];
You can try this:
$array = array(-50 , 60 , -4 , 80 , 25, -34, 15);
$max = max($array); //80
$min = min($array); //-50
$difference = $max - $min; //130
I have an array like this:
array (0 =>
array (
'id' => '20110209172713',
'Date' => '2011-02-09',
'Weight' => '200',
),
1 =>
array (
'id' => '20110209172747',
'Date' => '2011-02-09',
'Weight' => '180',
),
2 =>
array (
'id' => '20110209172827',
'Date' => '2011-02-09',
'Weight' => '175',
),
3 =>
array (
'id' => '20110211204433',
'Date' => '2011-02-11',
'Weight' => '195',
),
)
I need to extract minimal and maximal Weight values.
In this example
$min_value = 175
$max_value = 200
Any help on how to do this ?
Thank you !
Option 1. First you map the array to get those numbers (and not the full details):
$numbers = array_column($array, 'weight')
Then you get the min and max:
$min = min($numbers);
$max = max($numbers);
Option 2. (Only if you don't have PHP 5.5 or better) The same as option 1, but to pluck the values, use array_map:
$numbers = array_map(function($details) {
return $details['Weight'];
}, $array);
Option 3.
Option 4. If you only need a min OR max, array_reduce() might be faster:
$min = array_reduce($array, function($min, $details) {
return min($min, $details['weight']);
}, PHP_INT_MAX);
This does more min()s, but they're very fast. The PHP_INT_MAX is to start with a high, and get lower and lower. You could do the same for $max, but you'd start at 0, or -PHP_INT_MAX.
foreach ($array as $k => $v) {
$tArray[$k] = $v['Weight'];
}
$min_value = min($tArray);
$max_value = max($tArray);
For the people using PHP 5.5+ this can be done a lot easier with array_column. Not need for those ugly array_maps anymore.
How to get a max value:
$highest_weight = max(array_column($details, 'Weight'));
How to get the min value
$lowest_weight = min(array_column($details, 'Weight'));
It is interesting to note that both the solutions above use extra storage in form of arrays (first one two of them and second one uses one array) and then you find min and max using "extra storage" array. While that may be acceptable in real programming world (who gives a two bit about "extra" storage?) it would have got you a "C" in programming 101.
The problem of finding min and max can easily be solved with just two extra memory slots
$first = intval($input[0]['Weight']);
$min = $first ;
$max = $first ;
foreach($input as $data) {
$weight = intval($data['Weight']);
if($weight <= $min ) {
$min = $weight ;
}
if($weight > $max ) {
$max = $weight ;
}
}
echo " min = $min and max = $max \n " ;
How about without using predefined functions like min or max ?
//find max
$arr = [4,5,6,1];
$val = $arr[0];
$n = count($arr);
for($i=0;$i<$n;$i++) {
if($val < $arr[$i]) {
$val = $arr[$i];
}
}
echo $val;
//find min
$arr = [4,5,6,1];
$val = $arr[0];
$n = count($arr);
for($i=0;$i<$n;$i++) {
if($val > $arr[$i]) {
$val = $arr[$i];
}
}
echo $val;
$num = array (0 => array ('id' => '20110209172713', 'Date' => '2011-02-09', 'Weight' => '200'),
1 => array ('id' => '20110209172747', 'Date' => '2011-02-09', 'Weight' => '180'),
2 => array ('id' => '20110209172827', 'Date' => '2011-02-09', 'Weight' => '175'),
3 => array ('id' => '20110211204433', 'Date' => '2011-02-11', 'Weight' => '195'));
foreach($num as $key => $val)
{
$weight[] = $val['Weight'];
}
echo max($weight);
echo min($weight);
<?php
$array = array (0 =>
array (
'id' => '20110209172713',
'Date' => '2011-02-09',
'Weight' => '200',
),
1 =>
array (
'id' => '20110209172747',
'Date' => '2011-02-09',
'Weight' => '180',
),
2 =>
array (
'id' => '20110209172827',
'Date' => '2011-02-09',
'Weight' => '175',
),
3 =>
array (
'id' => '20110211204433',
'Date' => '2011-02-11',
'Weight' => '195',
),
);
foreach ($array as $key => $value) {
$result[$key] = $value['Weight'];
}
$min = min($result);
$max = max($result);
echo " The array in Minnumum number :".$min."<br/>";
echo " The array in Maximum number :".$max."<br/>";
?>
$Location_Category_array = array(5,50,7,6,1,7,7,30,50,50,50,40,50,9,9,11,2,2,2,2,2,11,21,21,1,12,1,5);
asort($Location_Category_array);
$count=array_count_values($Location_Category_array);//Counts the values in the array, returns associatve array
print_r($count);
$maxsize = 0;
$maxvalue = 0;
foreach($count as $a=>$y){
echo "<br/>".$a."=".$y;
if($y>=$maxvalue){
$maxvalue = $y;
if($a>$maxsize){
$maxsize = $a;
}
}
}
echo "<br/>max = ".$maxsize;
print fast five maximum and minimum number from array without use of sorting array in php
:-
<?php
$array = explode(',',"78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 81, 76, 73,
68, 72, 73, 75, 65, 74, 63, 67, 65, 64, 68, 73, 75, 79, 73");
$t=0;
$l=count($array);
foreach($array as $v)
{
$t += $v;
}
$avg= $t/$l;
echo "average Temperature is : ".$avg." ";
echo "<br>List of seven highest temperatsures :-";
$m[0]= max($array);
for($i=1; $i <7 ; $i++)
{
$m[$i]=max(array_diff($array,$m));
}
foreach ($m as $key => $value) {
echo " ".$value;
}
echo "<br> List of seven lowest temperatures : ";
$mi[0]= min($array);
for($i=1; $i <7 ; $i++)
{
$mi[$i]=min(array_diff($array,$mi));
}
foreach ($mi as $key => $value) {
echo " ".$value;
}
?>