Nam Tran
Nam Tran

Reputation: 11

How to optimize if-statemnts php?

How to optimize PHP?? I'd like to optimize this code with if-statements in PHP.

$head =  make_number($_GET['id']);
if(isset($head)){
    echo $head;
}
else {
    $head =  make_number($_GET['id']);
    if(isset($head)){
        echo $head;
    }
    else {
        $head =  make_number($_GET['url']);
        if(isset($head)){
            echo $head;
        }
    }
}

Upvotes: 1

Views: 85

Answers (4)

Agnius Vasiliauskas
Agnius Vasiliauskas

Reputation: 11267

You can use null coalescing operator from new PHP features:

$head = make_number($_GET['id']) ?? 
        make_number($_GET['url']) ?? 
        make_number($_GET['xyz']);

Or if you can't use php 7 features - use short-circuit OR's:

$head = make_number($_GET['id']) or 
$head = make_number($_GET['url']) or 
$head = make_number($_GET['xyz']);

Upvotes: 2

N.DeNisse
N.DeNisse

Reputation: 149

Here are my 2 cents:

if(isset($_GET['id'])){
      echo make_number($_GET['id']);
 }
elseif(isset($_GET['url'])){
      echo make_number($_GET['url']);
 }
 // if none of them is set
else{

      echo 'Nothing to echo';
}

Hope it helps

Upvotes: 0

Augusto Accorsi
Augusto Accorsi

Reputation: 327

do this

$headID = make_number($_GET['id']);
$headURL = make_number($_GET['url']);

if(isset($headID))
    echo $headID;
else {
    if(isset($headURL))
        echo $headURL;
}

Upvotes: 0

moffeltje
moffeltje

Reputation: 4658

Try this

$head1 = make_number($_GET['id']);
$head2 = make_number($_GET['url']);

if(isset($head1) && isset($head2)){
    echo $head;
}

Upvotes: 0

Related Questions