0

Right now I am using this code to grab a variable in my URL:

<?php

$transaction_id = $_GET['transaction_id'];

if($transaction_id == "") {
$transaction_id = 'NA';
}

?>

So far I have only been grabbing that single variable, but now I need to grab a total of 5 variables. Will everything still work properly and operate fast and smoothly if I just copy and paste multiple codes right next to each other like this:

<?php

$transaction_id = $_GET['transaction_id'];

if($transaction_id == "") {
$transaction_id = 'NA';
}

?>
<?php

$transaction_id2 = $_GET['transaction_id2'];

if($transaction_id2 == "") {
$transaction_id2 = 'NA';
}

?>
<?php

$transaction_id3 = $_GET['transaction_id3'];

if($transaction_id3 == "") {
$transaction_id3 = 'NA';
}

?>

Or is there a more efficient way to combine them all into one code?

Thanks for the help.

3
  • Combine them all into one <?php ... ?> block. Commented Nov 20, 2013 at 17:08
  • You can use something like $transaction_id3 = ($_GET['transaction_id3']!="") ? $_GET['transaction_id3']:'NA'; instead of assign the variable and then check Commented Nov 20, 2013 at 17:08
  • yes that will work fine, but you don't need to close and then reopen the <?php tags after each one Commented Nov 20, 2013 at 17:08

3 Answers 3

1

Make use of isset() construct

<?php
if(!isset($_GET['transaction_id'])) {
$transaction_id = 'NA';
}
if(!isset($_GET['transaction_id2'])) {
$transaction_id2 = 'NA';
}
if(!isset($_GET['transaction_id3'])) {
$transaction_id3 = 'NA';
}
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Maybe $transaction_id3 = (isset($_GET['transaction_id3']) && !empty($_GET['transaction_id3'])) ? $_GET['transaction_id3']:'NA'; ?
0

justo to be sure them all are setted and not empty

$na = 'NA';    

$transaction_id = (isset($_GET['transaction_id']) && $_GET['transaction_id'] != '') ? $_GET['transaction_id'] : $na ;
$transaction_id2 = (isset($_GET['transaction_id2']) && $_GET['transaction_id2'] != '') ? $_GET['transaction_id2'] : $na ;
...

Comments

0

you could do a for loop

<?php 
    $transaction_id = array();
    for($i=1;$i<6:$i++){
        if( $_GET['transaction_id'.$i] == "") {
            $transaction_id[] = 'NA'
        }else{
            $transaction_id[] = $_GET['transaction_id'.$i]
        }
    }
?>

This will make an array of transaction ids or NA

[0] => NA
[1] => 12345
[2] => 67890
[3] => 23454
[4] => NA
[5] => 55422

I don't know if this is better practice or not, maybe its just a different way. Hope it helps.

P.S. you will have to change your first $_GET['transaction_id']; to $_GET['transaction_id1'];

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.