My case is i have price of an item in a range of Kilogram, like
price in range 0.01-0.04 is 5
price in range 0.05-0.09 is 30
price in range 0.1-0.15 is 50
Here is sample of array like i want
$prices = array("0.01-0.04"=>5,"0.05-0.09"=>30);
now i want to make an array so when user input 0.02 it should return price in range 0.01-0.04
which is 5, similarly if user input 0.07 so it should return 30
.
how to make an array in PHP to access array via a range of indexes?
Try This code
<?php
$price = array(
array(
'min_range' => 0.1,
'max_range' => 0.4,
'price' => 5
),
array(
'min_range' => 0.5,
'max_range' => 0.9,
'price' => 30
),
array(
'min_range' => 1.0,
'max_range' => 1.5,
'price' => 50
),
);
$input = 0.7;
foreach( $price as $p){
if($input>=$p['min_range'] && $input<=$p['max_range']){
echo $p['price'];
break;
}
}
?>
set $no variable as number for which you are finding the range
<?php
$no = 0.05;
$ranges = array
(
array(0.01,0.04,5),
array(0.05,0.09,30),
array(0.1,0.15,50)
);
$foundFlag=false;
foreach ($ranges as $range) {
if($no>=$range[0] && $no<=$range[1])
{
$foundFlag=true;
echo "$range[2]";
}
}
if($foundFlag==false)
{
echo "range not found";
}
?>
You can try it in that way as well,
<?php
$input = $_POST['userInput'];
$count = 0;
$arr =Array();
$arr[0]=0.01;
$arr[1]=0.04;
$arr[2]=0.05;
$arr[3]=0.09;
$arr[4]=0.1;
$arr[5]=0.15;
$price =Array();
$price[0] =5;
$price[2] =30;
$price[4] =50;
while(count($arr)>$count)
if($arr[$count] != null && $arr[$count+1] != null)
{
if($input >$arr[$count] && $input <$arr[$count+1])
{
echo "price is $price[$count]";
}
}
$count = $count +2;
}
?>
I found something that looks it could be used for your condition
Php - Calculating number based on percentage, how to drop all precision after 2 dec places?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.