Search code examples
phparraysfiltermapping

Determine qualifying value from one array and access related values from other arrays with the same index


I have three different arrays

price = Array
(
    [0] => 200
    [1] => 300
    [2] => 400
    [3] => 500
)

package = Array
(
    [0] => 100040
    [1] => 100041
    [2] => 100042
    [3] => 100043
)

NoOfClients =Array
(
    [0] => 100
    [1] => 200
    [2] => 400
    [3] => 750
)

In need to get package and price based on NoOfClients . Example: If i have client count is 350, So my package is 100042 and price = 400. For more understand below i show one if else condition

clients = 350;
if (clients <= NoOfClients[0]) {
    plan = 100040
    price = 200
} elseif (clients > NoOfClients[0] and clients <= NoOfClients[1]) {
    plan = 100041
    price = 300
} elseif (clients > NoOfClients[1] and $clients <= NoOfClients[2]) {
    plan = 100042
    price = 400
} else {
    plan = 100043
    price = 500
}

My question is how will I get the dynamic result (plan and price) based on three different arrays and passing client count.


Solution

  • $clients = 10;
    
    $i = -1;
    foreach($NoOfClients as $item) {
       $i++;
       if ($clients < $item) break;
    }
    
    echo $plan = $package[$i];
    echo $price = $price[$i];