Given as an example:
$store = {A, B, C, D, E}
$price = {2, 10, 1, 500, 20}
Store[0]'s value is 2, [1] is 10, and so on. I'd like to know how to do that. I tried using min() but to no avail (unless I missed something out). Here's what I've done so far:
$x;
for ($x = $price.Count - 1; $x >= 0; $x--)
{
//this is the part where I can't figure it out
//compare prices here
//get the lowest price
//x = theSubstringOfTheLowestPrice
}
echo $store[x];
Your PHP code is not valid: $price = {A}
means you must have constant A and php arrays are enclosed with array()
or []
.
Use array_combine()
to create key-value pairs (demo):
$store = ['A', 'B', 'C', 'D', 'E'];
$price = [2, 10, 1, 500, 20];
$range = array_combine($store, $price);
var_dump($range['D']); // 500
Try this:
$store = array(A, B, C, D, E);
$price = array(2, 10, 1, 500, 20);
$index=array_search(min($price), $price);
echo $store[$index];
Instead of storing these key, value pairs in 2 separate arrays, let's associate them with one like so:
>>>$storePrices = [
"A" => 2,
"B" => 10,
"C" => 1,
"D" => 500,
"E" => 20
]
Now to get the lowest store price in your $storePrices
array, use can use min()
.
>>>min($storePrices)
=> 1
If you wish to get the associated store from the given minimum price, you can achieve it like this:
>>>array_search(1, $storePrices)
=> "C"
Or
>>>array_search(min($storePrices), $storePrices)
=> "C"
You can use associative arrays like this:
$prices = [ 'A' => 20, 'B' => 30, 'C' => 10];
And then calculate the minimum price like so:
$result = array_keys($prices, min($prices));
Here is the var_dump for $result
:
array(1) {
[0] =>
string(1) "C"
}