Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get specific value in an array based on the another value using PHP

I am having a problem getting the right value in the array. I have an array that has a key of moq and costunit. I want to get the costunit if the moq is less than or equal to the given quantity. I have the following array.

Array
(
    [moq] => 1000
    [costunit] => 0.44
)
Array
(
    [moq] => 20000
    [costunit] => 0.33
)
Array
(
    [moq] => 30000
    [costunit] => 0.30
)

Example 1: if the given qty is 25000 then the cost unit would be displayed is 0.33

Example 2: if the given qty is 1230 then the cost unit would be displayed is 0.44

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$get_prices = array(
  array(
   'moq'=> 1000
   'costunit'=> 0.44
   ),
 array(
   'moq'=> 20000
   'costunit'=> 0.33
   ),
 array(
   'moq'=> 30000
   'costunit'=> 0.30
   ),
);
$get_quantity = 30000;
foreach($get_prices as $get_price){

  if($get_price['moq'] >= $get_quantity){
    echo '<pre>';
        print_r($get_price['costunit']);
    echo '</pre>';
   }
}

>Solution :

All I think you need is a break in the loop so it stops when it find the first valid value

$get_prices = array(
  array( 'moq'=> 1000, 'costunit'=> 0.44 ),
  array( 'moq'=> 20000,'costunit'=> 0.33 ),
  array( 'moq'=> 30000, 'costunit'=> 0.30 )
);
$get_quantity = 1250;
foreach($get_prices as $get_price){

  if($get_price['moq'] >= $get_quantity){
    echo '<pre>';
        print_r($get_price['costunit']);
    echo '</pre>';
    break;
   }
}

RESULT

<pre>0.33</pre>

NOTE: I think your examples are wrong, have another look at what you said because it seems it is exactly what the code did, apart from not stopping when it found the first valid value

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading