Reputation: 301
I need to get the lowest among the values of 5 variables.
I want that if a variable is not set or it is empty, the script must exclude this variable from the results.
$var1='17';
$var2='19';
$var3='20';
$var4='1';
$var5='';
$arr = compact('var1','var2','var3','var4','var5'); // Stores values in array $arr
$highval = max($arr);
$lowval = min($arr);
$stores=count(array_filter($arr));
echo 'Item is available in '.$stores.' vars and is between '.$lowval.' and '.$highval.'';
For example assigning $var4=''
, the lowest value would be $var1
and not $var4
. There can also be multiple variables as not set or empty.
How would you edit the script above to accomplish it?
Upvotes: 0
Views: 105
Reputation: 741
$arr have String values in the array so need to convert in number then your problem will solve.
Add line : $arr = array_map('intval', $arr);
line for convert in number.
Try this:
$var1='17';
$var2='19';
$var3='20';
$var4='1';
$var5='';
$arr = compact('var1','var2','var3','var4','var5'); // Stores values in array $arr
$arr = array_map('intval', $arr);
$arr1 = array_filter($arr, function($a) { return ($a !== 0); }); // Remove if Array value have 0
$highval = max($arr1);
$lowval = min($arr1);
$stores=count($arr);
echo 'Item is available in '.$stores.' vars and is between '.$lowval.' and '.$highval.'';
Ourput :
Item is available in 4 vars and is between 1 and 20
Upvotes: 3
Reputation: 4860
If you are using array_filter
to show count, then you can use it before min/max. The code should like:
<?php
$var1 = '17';
$var2 = '19';
$var3 = '20';
$var4 = '1';
$var5 = '';
$arr = compact('var1', 'var2', 'var3', 'var4', 'var5'); // Stores values in array $arr
$filtered = array_filter($arr);
$highval = max($filtered);
$lowval = min($filtered);
$stores = count($filtered);
echo 'Item is available in ' . $stores . ' vars and is between ' . $lowval . ' and ' . $highval . '';
UPDATE
It would be better if you take array of numbers and write it like:
$arr = ['17', '19', '20', '1', ''];
$filtered = array_filter($arr);
$highval = max($filtered);
$lowval = min($filtered);
$stores = count($filtered);
echo 'Item is available in ' . $stores . ' vars and is between ' . $lowval . ' and ' . $highval . '';
Upvotes: 2