0

I want to create an if statement dynamically in PHP, but I don't know how to do this. For example, I am creating an Excel with different heights, widths and prices.

If my valueWidth < width the price is equal to the width price above.

enter image description here

If my width = 2050 and height = 2560, the prices is 621$.

The width, height and prices is entered dynamically and can be different from 3 numbers. Width, height and prices is Array.

width = [2000,3025,4036]
height = [2214,2411,2608]
class_1 = [245,272,302]
class_2 = [537,584,621]
class_3 = [755,799,836]
class_X = [...]

Can you help me find how to do the conditions effectively, please ?

3
  • What have you tried so far? Commented Nov 14, 2020 at 17:04
  • I try to do with If condition but it's not dynamically, if I add other values Commented Nov 14, 2020 at 17:07
  • Do you want extract the numbers from the characters? Or Do you want get a list of values (height & width) as an array?? Commented Nov 14, 2020 at 17:22

1 Answer 1

2

You may be aware of associative arrays, where you have a named key and a value:

$data = array('keyName' => 'value');
print $data['keyName']; 
// ==> 'value'

But for a grid, you need two indexes:

$grid = array(
  'rowName' => array(
    'colName' => 'rowColValue'
  )
);
print $grid['rowName']['colName'];
// == 'rowColValue'

So to condense all your data into one place, it would look like this:

$grid['2000']['2214'] = 245;
$grid['2000']['2411'] = 272;
$grid['2000']['2680'] = 302;
$grid['3025']['2214'] = 537;
$grid['3025']['2411'] = 584;
$grid['3025']['2086'] = 621;
$grid['4036']['2214'] = 755;
$grid['4036']['2411'] = 799;
$grid['4036']['2680'] = 836;

$width = '3025';
$height = '2411';

print $grid[$width][$height];

//==> 584

Assignment is just as easy as getting the results:

// assume $width. $height, and $price are user input, properly validated
$grid[$width][$height] = $price;

Alternately, if you need to build this from the arrays you supplied:

width = [2000,3025,4036]
height = [2214,2411,2608]
class_1 = [245,272,302]
class_2 = [537,584,621]
class_3 = [755,799,836]
class_X = [...]

Build a nested loop something like this:

$prices = [];
$prices[] = $class_1;
$prices[] = $class_2;
$prices[] = $class_3;
// etc.

$grid = [];
$classNumber = 0;
foreach($width as $w) {
  foreach($height as $h) {
    $grid[$w][$h] = $prices[$classNumber];
  }
  $classNumber++;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.