First of all I want to say I am not a programmer but I have been playing around with some simple php scripts today and I have a quick question for those in the know. How could I simplify the following code so it does not use all of those OR logical operators?
$number = "";
if ("$number" == 2 || "$number" == 3 || "$number" == 8 || "$number" == 10)
{
echo ('Your number is ' . "$number");
}
Thanks, Kris
you could do this:
$valid_numbers = array(2, 3, 8, 10);
if (in_array($number, $valid_numbers)) {
echo 'Your number is ', $number;
}
p.s.: you don't need/it's wrong to put $number between quotes, since you're expecting an int.
hope this helps
<?php
if (in_array($number,array(2,3,8,10))) {
echo 'Your number is '.$number;
}
or
<?php
switch ($number) {
case 2:
case 3:
case 8:
case 10:
echo 'Your number is '.$number;
break;
case 99;
echo 'Your number is 99';
break;
}
You can't make it simpler in a way that makes sense. I would keep it just like that.
EDIT: By "simplification" I would guess that you want to do less operations...
Firstly, although quotations around your variables don't cause the code to break, you really really don't need them and in fact the only reason your code still works is because PHP has a strange system to match between strings and integers.
Anyway, one way to rewrite that code is as
$validNumbers = array(2,3,8,10);
if (in_array($number, $validNumbers))
{
echo ('Your number is '. $number);
}
Technically, you could also do
if ((1 << $number) & 1292)
if you're into unreadable code. This works because the binary representation of 1292 has a 1 exactly at the binary digits 2, 3, 8, and 10.