1

I have URL below:

session.php?action=create_program

Then I have the following piece of code:

if( isset($_GET['action']) ){ $action= $_GET['action']; $action=''; }

It returns an empty string while it should return ''create_program'

4
  • 1
    ... you set it to an empty string with $action='';.... Commented Mar 2, 2018 at 11:20
  • I check the condition, if the $_GET is not set then I set it to empty, otherwise it should be equal to the $_get Commented Mar 2, 2018 at 11:21
  • looks like you want else with $action=''; Commented Mar 2, 2018 at 11:21
  • 1
    @DaniM Well, that's not the code you've written. Commented Mar 2, 2018 at 11:22

4 Answers 4

5

I think you were trying to set it to empty if you didn't receive anything in your get request. So either do it like this

if( isset($_GET['action']) ){
    $action= $_GET['action'];
} else {
    $action='';
}

Or, even simpler, give a default value that remains set if the get parameter is absent.

$action = '';
if( isset($_GET['action']) ){
    $action= $_GET['action'];
}

Finally, as suggested by Cashbee in the comment below, you can use the ternary operator to check whether $_GET['action'] was set and, in case it's not, give a default value to $action.

$action = isset($_GET['action']) ? $_GET['action'] : '';
Sign up to request clarification or add additional context in comments.

1 Comment

You could even shorten that with ternary operator: $action = isset($_GET['action']) ? $_GET['action'] : '';
2

Easy is the use of the ternary operator like this:

$action = isset($_GET['action']) ? $_GET['action'] : '';

You should always check if the variable is set or empty.

$action = empty($_GET['action']) ? '' : $_GET['action'];

Or even better, use the PHP filter functions.

$action = filter_input(INPUT_GET, 'action');

This has the advantage, you can even use rules, to give the appropriate result, like described in http://php.net/manual/de/function.filter-input.php

Comments

1

You are setting $action to empty at last that's why it is returning an empty string

if( isset($_GET['action']) )
{
  $action= $_GET['action'];
// $action='';  //Just remove this code
}

Comments

1
//$action will be empty if not have $_GET['action'];, just for PHP7
$action = $_GET['action'] ?? '';

hope can help you!

2 Comments

Thank you, but when I echo the $action, then I get 1
Did you mean ??? Or perhaps ?:?

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.