Retrieve $_GET properties in a single statement - php

Currently, I check to see if a $_GET or $_POST property is set by using empty(). Like this:
$status = null;
if (!empty($_GET['foo'])) {
$status = $_GET['foo'];
}
I imagine there is an even more concise way of doing the same thing built into PHP, that like what I'm doing now with empty, also avoids printing the notice saying undefined index. Maybe something like this:
$status = something($_GET['foo']);
Or, maybe I should just ignore the notice and do:
$status = $_GET['foo'];

I'm not sure what the problem is as empty() does not generate a warning for undefined variables, but if you want it in one line, you can use a ternary expression:
$status = empty($_GET['foo']) ? null : $_GET['foo'];

How about this if you want just GET:
$status = isset($_GET['foo'])?$_GET['foo']:NULL;
Or this if you want just GET and POST:
$status = isset($_GET['foo'])?$_GET['foo']:(isset($_POST['foo'])?NULL);

You can always check if the key in the $_GET array exists and set the variable to null if it isn't. Will never throw a notive.
$status = array_key_exists('foo', $_GET) ? $_GET['foo'] : null;

You can suppress the warnings by using #.
$status = #$_GET['foo'];

Related

Function to Avoid Variable Undefined

I am trying to write a function to avoid getting variable undefined error. Right now, i have a code like this:
function check($str){
if(isset($str)){
$s = $str;
} else {
$s = "";
}
}
check($_GET['var']);
The get var is not set. I am getting a variable undefined error on my screen. How do i alter my function to not throw this error and just return "" if it is not set? I don't want to have to code 100 if statements to avoid getting variable undefined. Thanks.
We already have in PHP a construct to check that. It is called isset(). With it you can check whether a variable exists. If you would like to create it with some default values if it doesn't exist yet, we also have syntax for it. It's null-coalescing operator.
$_GET['var'] = $_GET['var'] ?? '';
// or since PHP 7.4
$_GET['var'] ??= '';
Although I'm not sure if it is the right way of doing it, for the sake of providing an answer you can pass the variable by reference, this allows you to get away with passing undefined variables and check if it is set inside the function..
function check(&$str){
if(!isset($str)){
$str = "not set";
}
}
check($_GET['var']);
echo $_GET['var'];

Using Ternary Operator without the Else statement PHP

Can you use the Ternary Operator in PHP without the closing 'else' statement? I've tried it and it's returning errors. Google search isn't yielding anything, so I think the answer is probably no. I just wanted to double check here. For instance:
if ( isset($testing) {
$new_variable = $testing;
}
Will only set $new_variable if $testing exists. Now I can do
$new_variable = (isset($testing) ? $testing : "");
but that returns an empty variable for $new_variable if $testing isn't set. I don't want an empty variable if it's not set, I want the $new_variable to not be created.
I tried
$new_variable = (isset($testing) ? $testing);
and it returned errors. I also tried
$new_variable = (isset($testing) ? $testing : );
and it also returned errors. Is there a way to use the Ternary Operator without the attached else statement, or am I stuck writing it out longhand?
EDIT: Following Rizier123's advice, I tried setting the 'else' part of the equation to NULL, but it still ends up appending a key to an array. The value isn't there, but the key is, which messes up my plans. Please allow me to explain further.
The code is going to take a bunch of $_POST variables from a form and use them for parameters in a stdClass which is then used for API method calls. Some of form variables will not exist, as they all get applied to the same variable for the API call, but the user can only select one. As an example, maybe you can select 3 items, whichever item you select gets passed to the stdClass and the other 2 don't exist.
I tried this:
$yes_this_test = "IDK";
$setforsure = "for sure";
$list = new stdClass;
$list->DefinitelySet = $setforsure;
$list->MaybeSet = (isset($yes_this_test) ? $yes_this_test : NULL);
$list->MaybeSet = (isset($testing) ? $testing : NULL);
print_r($list);
But obviously MaybeSet gets set to NULL because (isset($testing) comes after (isset($yes_this_test) and it returns
stdClass Object ( [DefinitelySet] => for sure [MaybeSet] => )
I won't know what order the $_POST variables are coming in, so I can't really structure it in such a way to make sure the list gets processed in the correct order.
Now I know I can do something like
if ( isset($yes_this_test ) {
$list->MaybeSet = $yes_this_test;
}
elseif ( isset($testing) ) {
$list->MaybeSet = $testing;
}
But I was hoping there was a shorthand for this type of logic, as I have to write dozens of these. Is there an operator similar to the Ternary Operator used for if/elseif statements?
Since PHP 5.3 you can do this:
!isset($testing) ?: $new_variable = $testing;
As you can see, it only uses the part if the condition is false, so you have to negate the isset expression.
UPDATE
Since PHP 7.0 you can do this:
$new_variable = $testing ?? null;
As you can see, it returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
UPDATE
Since PHP 7.4 you can do this:
$new_variable ??= $testing;
It leaves $new_variable alone if it isset and assigns $testing to it otherwise.
Just set it to NULL like this:
$new_variable = (isset($testing) ? $testing : NULL);
The you variable would return false with a isset() check.
You can read more about NULL in the manual.
And a quote from there:
The special NULL value represents a variable with no value. NULL is the only possible value of type null.
A variable is considered to be null if:
it has been assigned the constant NULL.
it has not been set to any value yet.
it has been unset().
Since PHP 7.0 you can do the following, without getting an ErrorException "Trying to get property 'roomNumber' of non-object":
$house = new House();
$nr = $house->tenthFloor->roomNumbers ?? 0
Assuming the property "tenthFloor" does not exist in the Class "House", the code above will not throw an Error.
Whereas the code below will throw an ErrorException:
$nr = $house->tenthFloor->roomNumbers ? $house->tenthFloor->roomNumbers : 0
You can also do this (short form):
isset($testing) ? $new_variable = $testing : NULL;
JUST USE NULL TO SKIP STATEMENTS WHEN IT WRITTEN IN SHORTHAND
$a == $b? $a = 20 : NULL;

Shorter shorthand than ternary for setting variable to itself

I am trying to check if a variable is empty and if it is then set another variable to one string and if it's not then set the other variable to the first variable. Right now I am using a ternary operator, but I was wondering if there is an even shorter way to do this because it is setting it to a variable used in the logic.
Here is my code:
$company_name = $project->company->name;
$this->project['company_name'] = !empty($company_name)
? $company_name
: "Company";
If you have PHP 5.3+ you can use ?: but other than that no.
$this->project['company_name'] = $company_name ?: "Company";
Empty variables should evaluate to false and assign "Company".
try make a function for more variables pass values in it. you can check multiple variables using this. else i think no way to do check you to use and set other values same like (you are already using shorten)
$check = mycheck($check, 'mysting');
function mycheck($check, 'mysting') {
$return = (!empty($check) ? $check : "mysting");
return $return;
}
$this->project['company_name'] = !empty($project->company->name)
? $project->company->name
: "Company";
You can use in your function call variable=company. Then omit the ternary operator.
function xyz ($company="company") {
if ($this->project['company_name']) {
$company=$this->project['company_name'] ;
}
function even doesn't need return, depends on the usage.

How is an undefined variable initialized/interpreted by PHP?

Well, I have to remove warnings of an existing PHP 5.4 script and I am not sure how to handle the following prob correctly.
I got a source code like
if ($start_id_minus >= 0)
{
$tmp_link = $link."&id=$start_id_minus";
$tmp_html_previous .= "<a href='$tmp_link'><< previous</a> ";
}
Which results in a notice like "Notice: Undefined variable: $tmp_html_previous in <5 lines below>"
So what I have to do is to initialize the variable before this "if".
In this case it is obvious that $tmp_html_previous is a string, so what I could do is:
$tmp_html_previous = '';
But I got many similiar case where the "type" of the variable is not obvious to me. So how do I initialize these variables correctly? With NULL? With 0? With ''? Not at all: var $tmp;?
0 is the obvious initial value for any variables you're going to do mathematical operations on.
true or false is the obvious initial value for "boolean variables".
null is a good initial value for anything else.
In this case, since it looks as if you're building a string, you could use:
$tmp_html_previous = '';
Or:
$tmp_html_previous = NULL;
If $tmp_html_previous were a boolean value, you could set the default as true or false.
$tmp_html_previous = false;
If you're doing calculations:
$tmp_html_previous = 0;
Basically, it all depends on the logic of your application.
With whatever you want, the type will change automatically as PHP is not strongly typed.
Just whatever to initialize; if concerned about appending strings that do it string:
$tmp = isset($tmp) ? $tmp : '';
However, null is always the obvious solution.

isset PHP isset($_GET['something']) ? $_GET['something'] : ''

I am looking to expand on my PHP knowledge, and I came across something I am not sure what it is or how to even search for it. I am looking at php.net isset code, and I see isset($_GET['something']) ? $_GET['something'] : ''
I understand normal isset operations, such as if(isset($_GET['something']){ If something is exists, then it is set and we will do something } but I don't understand the ?, repeating the get again, the : or the ''. Can someone help break this down for me or at least point me in the right direction?
It's commonly referred to as 'shorthand' or the Ternary Operator.
$test = isset($_GET['something']) ? $_GET['something'] : '';
means
if(isset($_GET['something'])) {
$test = $_GET['something'];
} else {
$test = '';
}
To break it down:
$test = ... // assign variable
isset(...) // test
? ... // if test is true, do ... (equivalent to if)
: ... // otherwise... (equivalent to else)
Or...
// test --v
if(isset(...)) { // if test is true, do ... (equivalent to ?)
$test = // assign variable
} else { // otherwise... (equivalent to :)
In PHP 7 you can write it even shorter:
$age = $_GET['age'] ?? 27;
This means that the $age variable will be set to the age parameter if it is provided in the URL, or it will default to 27.
See all new features of PHP 7.
That's called a ternary operator and it's mainly used in place of an if-else statement.
In the example you gave it can be used to retrieve a value from an array given isset returns true
isset($_GET['something']) ? $_GET['something'] : ''
is equivalent to
if (isset($_GET['something'])) {
echo "Your error message!";
} else {
$test = $_GET['something'];
}
echo $test;
Of course it's not much use unless you assign it to something, and possibly even assign a default value for a user submitted value.
$username = isset($_GET['username']) ? $_GET['username'] : 'anonymous'
You have encountered the ternary operator. It's purpose is that of a basic if-else statement. The following pieces of code do the same thing.
Ternary:
$something = isset($_GET['something']) ? $_GET['something'] : "failed";
If-else:
if (isset($_GET['something'])) {
$something = $_GET['something'];
} else {
$something = "failed";
}
It is called the ternary operator. It is shorthand for an if-else block. See here for an example http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
? is called Ternary (conditional) operator : example
What you're looking at is called a Ternary Operator, and you can find the PHP implementation here. It's an if else statement.
if (isset($_GET['something']) == true) {
thing = isset($_GET['something']);
} else {
thing = "";
}
If you want an empty string default then a preferred way is one of these (depending on your need):
$str_value = strval($_GET['something']);
$trimmed_value = trim($_GET['something']);
$int_value = intval($_GET['somenumber']);
If the url parameter something doesn't exist in the url then $_GET['something'] will return null
strval($_GET['something']) -> strval(null) -> ""
and your variable $value is set to an empty string.
trim() might be prefered over strval() depending on code (e.g. a Name parameter might want to use it)
intval() if only numeric values are expected and the default is zero. intval(null) -> 0
Cases to consider:
...&something=value1&key2=value2 (typical)
...&key2=value2 (parameter missing from url $_GET will return null for it)
...&something=+++&key2=value (parameter is " ")
Why this is a preferred approach:
It fits neatly on one line and is clear what's going on.
It's readable than $value = isset($_GET['something']) ? $_GET['something'] : '';
Lower risk of copy/paste mistake or a typo: $value=isset($_GET['something'])?$_GET['somthing']:'';
It's compatible with older and newer php.
Update
Strict mode may require something like this:
$str_value = strval(#$_GET['something']);
$trimmed_value = trim(#$_GET['something']);
$int_value = intval(#$_GET['somenumber']);

Categories