6

Is there a shorter way of writing this?

<? 
if($_GET['id']==1 ||
$_GET['id']==3 ||
$_GET['id']==4 || 
$_GET['id']==5)
{echo 'does it really have to be this explicit?'};
?>

Something like this perhaps?

<?
if($_GET['id']==1 || 3 || 4 || 5){echo 'this is much shorter'};
?>

5 Answers 5

32

Just try with:

if ( in_array($_GET['id'], array(1, 3, 4, 5)) ) {}
Sign up to request clarification or add additional context in comments.

1 Comment

This is the shortest way I know. Additionally it's much easier to read.
4

Maybe not shorter but more readable. Try the in_array() function:

if (in_array($_GET['id'], array(1, 3, 4, 5)))
{
  echo "What about this?";
}

Comments

2

Perhaps switch may help

switch($_GET['id']) {
    case 1: 
    case 3: 
    case 4: 
    case 5:
        echo 'Slect maybe :P';
        break;
}

1 Comment

I don't know a function select() - can you point me to the manual on php.net? And who votes that up????
1

You can use regular expression like below:

preg_match(['1-4']);

Comments

0

Declare an array:

$values = array(1,3,4,5);

Get your variable

$id = $_GET['id'];

Now use PHP in_array();

if(in_array($id, $values)){
//do something
}

Read about in_array()

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.