I'm working with a PHP array that shows a range of prices, where an individual item is in the form of "price from-price to". Here's an example of the array:
Array
(
[0] => $625,000-$700,000
[1] => $550,000-$625,000
[2] => $1,000,000-$1,250,000
[3] => $925,000-$1,000,000
)
I now need to retrieve the lowest and highest price in the array, however as they are a range I first need to pull apart each price in each array item. For example using the above array I would like to be able to return something like this:
$minPrice = 550000;
$maxPrice = 1250000;
I'm new to PHP and completely stumped at this point about how to go about parsing each of the values from each array item then getting the lowest/highest value.
I would put all the normalized prices in an array and use the php max, min functions.
<?php
$ranges = array(
"$625,000-$700,000",
"$550,000-$625,000",
"$1,000,000-$1,250,000",
"$925,000-$1,000,000",
);
$prices = array();
foreach ($ranges as $range) {
$prices = array_merge($prices, explode("-", preg_replace("/[\\$,]/i", "", $range)));
}
$maxPrice = max($prices);
$minPrice = min($prices);
try this:
$array = Array
(
0 => '$625,000-$700,000',
1 => '$550,000-$625,000',
2 => '$1,000,000-$1,250,000',
3 => '$925,000-$1,000,000',
);
$tmp = array();
foreach($array as $key=>$value){
$cleanValue = explode('-', str_replace(array('$',','), array('',''), $value));
foreach($cleanValue as $k=>$v){
$tmp[] = $v;
}
}
$minValue = min($tmp);
$maxValue = max($tmp);
echo $minValue . ' '. $maxValue;
Please refer code below.
First value are exploded to an array and then "$" is removed and then value is converted to integer. Then values are added to array and finally min / max functions are called.
$maxPrice = 0;
$max_curr = 0;
$price_arr = array();
foreach($min_maxs as $min_max){
$min_max_arr = explode("-",$min_max); // string to array
array_walk($min_max_arr,"remove_dollar_commas"); // remove "$"
$price_arr = array_merge($price_arr , $min_max_arr ); // add to final array
}
$maxPrice = max($price_arr); // call max function to get maximum value
$minPrice = min($price_arr); // call min function to get minimum value
function remove_dollar_commas(&$subject){
$subject = intval( str_replace(array("\$",","), "", $subject) );
}
Related
I have two arrays and I want to link together when processing them.
$dat = array(
"2020-02-01",
"2020-02-05",
"2020-02-10",
"2020-02-12",
"2020-02-15"
);
$word = array(
"Attend To,Explore,Unaided,dull,bad"
);
//User input
$start = "2020-01-01";
$end = "2020-02-07";
I want the input to affect the second array too, so when the first array gets its result from first 2, then the second array too should have it from the first 2.
//Filter out dates between start and end date
$result = array_filter($dat, function($data_item) use($start, $end) {
return $data_item >= $start && $data_item <= $end;
});
and the result is
Array
(
[0] => 2020-02-01
[1] => 2020-02-05
)
I want it to be able to link $dat and $word so that the result for word too will be
Array
(
[0] => Attend To
[1] => Explore
)
I don't find functional programming to be very readable/attractive for this case. Just use a simple foreach loop and conditionally grab the words related by the shared indices.
Since the two arrays share common indices, it is unnecessary work to combine the two arrays -- just reference the indices.
Code: (Demo)
$dat = ["2020-02-01", "2020-02-05", "2020-02-10", "20-02-12", "2020-02-15"];
$word = ["Attend To,Explore,Unaided,dull,bad"];
$words = explode(',', $word[0]);
//User input
$start = "2020-01-01";
$end = "2020-02-07";
$result = [];
foreach ($dat as $index => $date) {
if ($date >= $start && $date <= $end) {
$result[] = $words[$index];
}
}
var_export($result);
Output:
array (
0 => 'Attend To',
1 => 'Explore',
)
The original keys will be maintained after array_filter, so get the entries for keys that are the same by computing the intersection. It appears that $word is a one element array with a string, so just explode it:
$word_result = array_intersect_key(explode(',', $word[0]), $result);
See a Demo.
If one of the arrays has unique values, you can combine the array and just operate on that.
$comb = array_combine(explode(',', $word[0]), $dat);
$result = array_filter($comb, function($data_item) use($start,$end) {
return $data_item >= $start && $data_item <= $end;
});
This yields:
Array
(
[Attend To] => 2020-02-01
[Explore] => 2020-02-05
)
You can use the array as is or use array_keys to get the keys as the $word array.
If it's not guaranteed to be $word[0] then you can use reset($word) or current($word).
A possible solution assuming that the arrays have the same keys (I changed it to reflect this), is to use the constant ARRAY_FILTER_USE_BOTH to array_filter, so that the key is available in the callback function.
here i fill a second array $result2 with the words while filtering the data (note that things are added in use and $result2 is passed by reference):
$dat = array("2020-02-01","2020-02-05","2020-02-10","20-02-12","2020-02-15");
$word = array("Attend To","Explore","Unaided","dull","bad");
//User input
$start = "2020-01-01";
$end = "2020-02-07";
//Filter out dates between start and end date
$result2 = [];
$result = array_filter($dat, function($data_item, $key) use($start, $end, $word, &$result2) {
if($data_item >= $start && $data_item <= $end){
$result2[$key] = $word[$key];
return true;
}
return false;
}, ARRAY_FILTER_USE_BOTH);
AbraCadaver's answer is perfect fit when only the filtering is needed, but this can be useful in case someone has to do extra operations in the filter callback..
I have code to get minimum and maximum value from comma separated value ranges by using below given code
<?php
$price=$_GET['price'];
$grade = str_replace('-', ',', $price);
$number = array($grade);
$max = max($number);
$min = min($number);
echo "min value is $min <br/>";
echo "max value is $max <br/>";
?>
for the input ?price=0-5,4-30,6-50 This should output minimum value 0 and maximum value 50 but my above code is giving output as
min value is 0,5,4,30,6,50
max value is 0,5,4,30,6,50
Kindly guide me where i am making mistake or any other working alternate.
You are incorrect with creating an array. Please use explode for this. Explode function will break the string into array.
First parameter is the character on which you want to split the string and the second one is input. In your case it would be nice to add the str_replace function right there, so you don't change the original input.
$input = '0-5,4-30,6-50';
$numbers = explode(',', str_replace('-', ',', $input));
And now you can use min and max functions and they will work properly.
After using str_replace method, you are converting a string into an array, your array looks like:
Array ( [0] => 0,5,4,30,6,50 )
With this array, you cant achieve or get the maximum and minimum value from an array.
You need to explode your string with comma as:
$yourArr = explode(",", $grade); // this will convert string into array.
Now your result should looks like:
Array ( [0] => 0 [1] => 5 [2] => 4 [3] => 30 [4] => 6 [5] => 50 )
Complete Example:
<?php
$price='0-5,4-30,6-50';
$grade = str_replace('-', ',', $price);
$yourArr = explode(",", $grade);
$max = max($yourArr);
$min = min($yourArr);
echo "min value is $min <br/>";
echo "max value is $max <br/>";
?>
Result:
min value is 0
max value is 50
<?php
$price = '0-5,4-30,6-50';
if(preg_match_all('/\d+/', $price, $matches)) {
$min = min($matches[0]);
$max = max($matches[0]);
var_dump($min, $max);
}
Output:
string(1) "0"
string(2) "50"
I have a php string formed by images and corresponding prices like OK Like
$myString = "ddb94-b_mgr3043.jpg,3800,83acc-b_mgr3059.jpg,4100";
I know that if I do:
$myArray = explode(',', $myString);
print_r($myArray);
I will get :
Array
(
[0] => ddb94-b_mgr3043.jpg
[1] => 3800
[2] => 83acc-b_mgr3059.jpg
[3] => 4100
)
But How could I split the string so I can have an associative array of the form?
Array
(
"ddb94-b_mgr3043.jpg" => "3800"
"83acc-b_mgr3059.jpg" => "4100"
)
Easier way to do like below:-
<?php
$myString = "ddb94-b_mgr3043.jpg,3800,83acc-b_mgr3059.jpg,4100";
$chunks = array_chunk(explode(',', $myString), 2); //chunk array into 2-2 combination
$final_array = array();
foreach($chunks as $chunk){ //iterate over array
$final_array[trim($chunk[0])] = trim($chunk[1]);//make key value pair
}
print_r($final_array); //print final array
Output:-https://eval.in/859757
Here is another approach to achieve this,
$myString = "ddb94-b_mgr3043.jpg,3800,83acc-b_mgr3059.jpg,4100,test.jpg,12321";
$arr = explode(",",$myString);
$temp = [];
array_walk($arr, function($item,$i) use (&$temp,$arr){
if($i % 2 != 0) // checking for odd values
$temp[$arr[$i-1]] = $item; // key will be even values
});
print_r($temp);
array_walk - Apply a user supplied function to every member of an array
Here is your working demo.
Try this Code... If you will receive all the key and value is equal it will work...
$myString = "ddb94-b_mgr3043.jpg,3800,83acc-b_mgr3059.jpg,4100";
$myArray = explode(',', $myString);
$how_many = count($myArray)/2;
for($i = 0; $i <= $how_many; $i = $i + 2){
$key = $myArray[$i];
$value = $myArray[$i+1];
// store it here
$arra[$key] = $value;
}
print_r($arra);
I have an array like this:
$a = array(
array('amount'=>10,'curr'=>'USD'),
array('amount'=>20,'curr'=>'JPY'),
array('amount'=>30,'curr'=>'BAT'),
array('amount'=>50,'curr'=>'BAT'),
array('amount'=>100,'curr'=>'USD')
);
I want to sum all amount the same currency together and return like this:
$total = array('BAT'=>80,
'JPY'=>20,
'USD'=>110
)
$total = array();
foreach($a as $arr){
if(!isset($total[$arr['curr']])){
$total[$arr['curr']] = 0;
}
$total[$arr['curr']] += $arr['amount'];
}
I want to replace all array values with 0 except work and home.
Input:
$array = ['work', 'homework', 'home', 'sky', 'door']
My coding attempt:
$a = str_replace("work", "0", $array);
Expected output:
['work', 0, 'home', 0, 0]
Also my input data is coming from a user submission and the amount of array elements may be very large.
A bit more elegant and shorter solution.
$aArray = array('work','home','sky','door');
foreach($aArray as &$sValue)
{
if ( $sValue!='work' && $sValue!='home' ) $sValue=0;
}
The & operator is a pointer to the particular original string in the array. (instead of a copy of that string)
You can that way assign a new value to the string in the array. The only thing you may not do is anything that may disturb the order in the array, like unset() or key manipulation.
The resulting array of the example above will be
$aArray = array('work','home', 0, 0)
A loop will perform a series of actions many times. So, for each element in your array, you would check if it is equal to the one you want to change and if it is, change it. Also be sure to put quote marks around your strings
//Setup the array of string
$asting = array('work','home','sky','door')
/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting);$i++){
//Check if the value at the 'ith' element in the array is the one you want to change
//if it is, set the ith element to 0
if ($asting[$i] == 'work' || $asting[$i] == 'home')
$asting[$i] = 0;
}
Here is some suggested reading:
http://www.php.net/manual/en/language.types.array.php
http://www.php.net/manual/en/language.control-structures.php
But if you are struggling on stuff such as looping, you may want to read some introductory programming material. Which should help you really understand what's going on.
A bit other and much quicker way, but true, need a loop:
//Setup the array of string
$asting = array('bar', 'market', 'work', 'home', 'sky', 'door');
//Setup the array of replacings
$replace = array('home', 'work');
//Loop them through str_replace() replacing with 0 or any other value...
foreach ($replace as $val) $asting = str_replace($val, 0, $asting);
//See what results brings:
print_r ($asting);
Will output:
Array
(
[0] => bar
[1] => market
[2] => 0
[3] => 0
[4] => sky
[5] => door
)
An alternative using array_map:
$original = array('work','home','sky','door');
$mapped = array_map(function($i){
$exclude = array('work','home');
return in_array($i, $exclude) ? 0 : $i;
}, $original);
you may try array_walk function:
function zeros(&$value)
{
if ($value != 'home' && $value != 'work'){$value = 0;}
}
$asting = array('work','home','sky','door','march');
array_walk($asting, 'zeros');
print_r($asting);
You can also give array as a parameter 1 and 2 on str_replace...
Just a small point to the for loop. Many dont realize the second comparing task is done every new iteration. So if it was a case of big array or calculation you could optimize loop a bit by doing:
for ($i = 0, $c = count($asting); $i < $c; $i++) {...}
You may also want to see http://php.net/manual/en/function.array-replace.php for original problem unless the code really is final :)
Try This
$your_array = array('work','home','sky','door');
$rep = array('home', 'work');
foreach($rep as $key=>$val){
$key = array_search($val, $your_array);
$your_array[$key] = 0;
}
print_r($your_array);
There are a few techniques on this page that make zero iterated function calls -- which is good performance-wise. For best maintainability, I recommend separating your list of targeted string as a lookup array. By modifying the original array values by reference, you can swiftly replace whole strings and null coalesce non-targeted values to 0.
Code: (Demo)
$array = ['work', 'homework', 'home', 'sky', 'door'];
$keep = ['work', 'home'];
$lookup = array_combine($keep, $keep);
foreach ($array as &$v) {
$v = $lookup[$v] ?? 0;
}
var_export($array);
Output:
array (
0 => 'work',
1 => 0,
2 => 'home',
3 => 0,
4 => 0,
)
You can very easily, cleanly extend your list of targeted strings by merely extending $keep.
If you don't want a classic loop, you can use the same technique without modifying the original array. (Demo)
var_export(
array_map(fn($v) => $lookup[$v] ?? 0, $array)
);
this my final code
//Setup the array of string
$asting = array('work','home','sky','door','march');
/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting); $i++) {
//Check if the value at the 'ith' element in the array is the one you want to change
//if it is, set the ith element to 0
if ($asting[$i] == 'work') {
$asting[$i] = 20;
} elseif($asting[$i] == 'home'){
$asting[$i] = 30;
}else{
$asting[$i] = 0;
}
echo $asting[$i]."<br><br>";
$total += $asting[$i];
}
echo $total;