Using ceil to get index of a PHP array
Вопрос
I'm trying to simplify some inherited PHP code that assigns a value to one variable based on the value in another variable, roughly mapping like this:
if x < 50, y = 10
else if x >= 50 and < 100, y = 20
else if x >= 100 and < 350, y = 30
else y = 40
The actual PHP code for this takes up several lines and is far from ideal, but there's enough of a pattern to it that I think I can greatly simplify it - but it's not a completely simple pattern either.
My best idea so far is to assign the possible y values to an array and then call the index of that array based on the ceiling of the x value, like this:
$convert = array (10, 20, 30, 30, 30, 30);
$y = ($x <= 350) ? $convert[ceil($x/50)] : 40;
Two lines, much less redundancy and much more flexibility. But I see that ceil
returns a float so I'm not sure if I can trust it to generate the index of an array, and I haven't found anything online about it either way. If it can possibly return some sort of 3.000000000001
value, am I safe just doing it like this:
$y = ($x <= 350) ? $convert[round(ceil($x/50))] : 40;
Or are there still potential pitfalls and/or a better solution?
Решение
ceil()
will never return anything besides an Integer as the documentation (even if it is cast as a float), and Dave pointed out.
Also, because of Type Juggling, it will be cast as an integer when you use it where an integer is expected. You should be 100% safe. The entire point of ceil is to round up to the nearest integer :-)
Другие советы
Note that your code
if x < 50, y = 10
else if x >= 50 and < 100, y = 20
else if x >= 100 and < 350, y = 30
else y = 40
can be simplified
<?php
if ($x < 50) { $y = 10; }
else if ($x < 100) { $y = 20; }
else if ($x < 350) { $y = 30; }
else { $y = 40; }
and althought it occupies some lines is easy to undersand and easy to mantain/modify without thinking so much what the code do.