Way to combine isset and variable assignment in PHP? - php

Is there a cleaner way to do the following:
if (isset($foo)) {
$bar = $foo;
}
It just seems redundant to check for a value, then assign it.

Maybe you could use
$var or $var = 'default value";

Slightly dirty using the # operator but:
if ($bar = #$foo) { //do something }

Related

Is it more efficient to declare a variable and change it if (something()) or should I use if and else?

Simple question, maybe a stupid question, but is it better to use
$var = 'value';
if (something()) $var = 'other value';
or
if (something()) $var = 'other value';
else $var = 'value';
?
And do I have to put something like $var = null; or $var = 'value' (in case something goes wrong with the following if and else statements) before the second variant for a nice code?
Really makes no difference, and depends on your preference. My personal preference is to declare the the variable first. This is just so that I know the variable exists, regardless of the if statement.
Choose whichever comes naturally.

understading the ternary operator in php

I'm reading someone else's code and they have a line like this:
$_REQUEST[LINKEDIN::_GET_TYPE] = (isset($_REQUEST[LINKEDIN::_GET_TYPE])) ? $_REQUEST[LINKEDIN::_GET_TYPE] : '';
I just want to make sure I follow this. I might have finally figured out the logic of it.
Is this correct?
If $_REQUEST[LINKEDIN::_GET_TYPE] is set, then assign it to itself. (meant as a do-nothing condition) otherwise set it to a null string. (Would imply that NULL (undefined) and "" would not be treated the same in some other part of the script.)
The ternary operator you posted acts like a single line if-else as follows
if (isset($_REQUEST[LINKEDIN::_GET_TYPE])) {
$_REQUEST[LINKEDIN::_GET_TYPE] = $_REQUEST[LINKEDIN::_GET_TYPE];
} else {
$_REQUEST[LINKEDIN::_GET_TYPE] = '';
}
Which you could simplify as
if (!(isset($_REQUEST[LINKEDIN::_GET_TYPE]))) {
$_REQUEST[LINKEDIN::_GET_TYPE] = '';
}
You missed the last part. If $_REQUEST[LINKEDIN::_GET_TYPE] is not set, then $_REQUEST[LINKEDIN::_GET_TYPE] is set to empty, not null. The point is that when $_REQUEST[LINKEDIN::_GET_TYPE] is called, that it exists but has no value.
Think of it this way
if(condition) { (?)
//TRUE
} else { (:)
//FALSE
}
So,
echo condition ? TRUE : FALSE;
if that makes sense
This
$foo = $bar ? 'baz' : 'qux';
is the functional equivalent of
if ($bar) { // test $bar for truthiness
$foo = 'baz';
} else {
$foo = 'qux';
}
So yes, what you're doing would work. However, with the newer PHP versions, there's a shortcut version of the tenary:
$foo = $bar ?: 'qux';
which will do exactly what you want
Your explanation is correct as far as my knowledge goes.
A ternary operator is like an if statement. The one you have would look like this as an if statement:
if( isset($_REQUEST[LINKEDIN::_GET_TYPE] ) {
$_REQUEST['LINKEDIN::_GET_TYPE] = $_REQUEST['LINKEDIN::_GET_TYPE];
} else {
$_REQUEST['LINKEDIN::_GET_TYPE] = ''; // It equals an empty string, not null.
}
Sometimes its easier to look at a ternary statement like a normal if statement if you are unsure on what is going on.
The statement you have seems to be doing what you say, setting the value to its self if it is set, and if it is not set, setting it to an empty string.

Proper way to declare multiple vars in PHP

I've been coding personal scripts for years in PHP and get used to turn off Error display. I'm about to release some of these scripts and would like to do it the proper way.
The only reason why I turn off error display is to avoid having to test every single var, prior using it, thanks to isset().
So, here is my question:
Is there a better way to declare multiple vars than this ?
<?php
// at the begining of my main file
if (!isset($foo)) ($foo = '');
if (!isset($bar)) ($bar = '');
if (!isset($ping)) ($ping = '');
if (!isset($pong)) ($pong = '');
// etc. for every single var
?>
Something like this for instance :
<?php
var $foo, $bar, $ping, $pong;
?>
<?php
$foo = $bar = $ping = $pong = '';
?>
If it's your script and you know which variables where you use, why you want spend recourses to check if the variable was declared before?
I posted this in a comment earlier, but someone suggested I submit it as an answer.
The shortest and simplest way I can think of, is to do:
$foo = $bar = $ping = $pong = '';
I often prefer to set things to false, instead of an empty string, so that you can always do checks in the future with === false, but that is just a preference and depends on how you are using these variables and for what.
Your if() with isset() attempt is the proper way of doing that!
But you can write it a little bit shorter/more readable, using the Ternary Operator:
$foo = isset($foo) ? $foo : '';
The first $foo will be set to the value after the ? when the condition after the = is true, else it will be set to the value after the :. The condition (between = and ? ) will always be casted as boolean.
Since PHP 5.3 you can write it even shorter:
$foo = isset($foo) ?: '';
This will set $foo to TRUE or FALSE (depending on what isset() returns), as pointed by #Decent Dabbler in the comments. Removing isset() will set it to '' but it will also throw an undefined variable notice (not in production though).
Since PHP 7 you can use a null coalesce operator:
$foo = $foo ?? '';
This won't throw any error, but it will evaluate as TRUE if $foo exists and is empty, as opposed to the shorthand ternary operator, that will evaluate as FALSE if the variable is empty.
A somewhat round-about way of doing this is if you put the name of your variables in an array, and then loop them with a Ternary Operator, similar to powtac's answer.
$vars = array('foo', 'bar', 'ping', 'pong');
$defaultVar = '';
foreach($vars as $var)
{
$$var = isset($$var) ? $$var : $defaultVar;
}
As mentioned in other answers, since version 5.3, PHP allows you to write the above code as follows:
$vars = array('foo', 'bar', 'ping', 'pong');
$defaultVar = '';
foreach($vars as $var)
{
$$var = isset($$var) ?: $defaultVar;
}
Note the changed Ternary Operator.
In OOP you can use this approach:
protected $password, $full_name, $email;
For non-OOP you declare them just in code they will be Undefined if you didn't assign any value to them:
$foo; $bar; $baz;
$set_foo = (isset($foo)) ? $foo : $foo = 'Foo';
echo $set_foo;
Why not just set them?
<?php
$foo = '';
$bar = '';
//etc
?>
If you're trying to preserve the value in them, then yes that's the correct way in general. Note that you don't need the second pair of brackets in your statements:
if (!isset($foo)) $foo = '';
is enough.
To fix the issue of
<?php
$foo = $bar = $ping = $pong = '';
?>
throwing
Notice: Undefined variable: ...
<?php
#$foo = $bar = $ping = $pong = '';
?>
It will not fix it but it will not be shown nd will not stop the script from parsing.

Test and echo without repetition?

This is a minor thing, but it's been bugging me for a while. I've wracked my brain for a way to write statements like this without any repetition of code. For example:
echo isset($array[0])? $array[0]: 'not set';
$var = empty($other_var)? '$other_var not set': $other_var;
Is there some sort of test-and-return (for the former) or test-and-set (for the latter) operator I don't know about? This may seem like a minor point, but the duplication seems unnecessary and can lead to very long lines that can complicate maintenance. Consider:
$another_var = array_key_exists($array[Utility::FindIndex($username)][Constants::App_CRITERION], $haystack[NthDimension('my dimensional indicator')])? $array[Utility::FindIndex($username)][Constants::App_CRITERION], $haystack[NthDimension('my dimensional indicator')]: 'not set';
Yes, yes, the above line is totally contrived but it's not unthinkable that something like this could occur. It just seems strange to me that there isn't a way to test something and assign it's value (if true) without repetition without repetition.
It won't handle the isset () case, which is a main use case for this pattern, but PHP 5.3 does have a short form for the ternary operator.
$new_val = $if_true ? $if_true : $if_false;
can be shortened to
$new_val = $if_true ?: $if_false;
I couldn't find it in the docs, strangely, but here's a question about it: What is ?: in PHP 5.3?
I think in PHP 6 there was a function planned called issetor or something similar. But I can't remember the name. And PHP 6 is dead either way.
So, write it yourself:
function issetor(&$var, $default) {
return isset($var) ? $var : $default;
}
echo issetor($_GET['me'], 'you');
If you want to make it even more abstract, look at this:
function isor(&$var, $default, $condition) {
if (!is_callable($condition)) {
throw new InvalidArgumentExpression('condition not callable!');
}
return $condition($var) ? $var : $default;
}
// this is equivalent to issetor($_GET['me'], 'you');
echo isor($_GET['me'], 'you', function(&$var) { return isset($var); });
// but you may use a more complicated thing here, too:
echo isor($_GET['me'], 'you', function($var) use($allowed) { return in_array($var, $allowed); });
// this is equivalent to:
echo in_array($_GET['me'], $allowed) ? $_GET['me'] : 'you';
// now the "normal" version is still shorter. But using isor allows you to store often used $condition closures in variables. For example, if you want to check if several values are in an array, you could write:
$isAllowed = function ($var) use ($allowed) {
return in_array($var, $allowed);
};
$a = isor($a, 'default', $inAllowed);
$b = isor($b, 'default', $inAllowed);
$c = isor($c, 'default', $inAllowed);
$d = isor($d, 'default', $inAllowed);
If you want to pass additional variables to your condition function without always useing closures you may add another argument. (Note I didn't use an argument array and call_user_func_array, because you may not pass per reference using it, but obviously you may extend the code so it does so.)
function isor(&$var, $default, $condition, $addArgument = null) {
if (!is_callable($condition)) {
throw new InvalidArgumentExpression('condition not callable!');
}
return $condition($var, $addArgument) ? $var : $default;
}
// the above in_array condition:
echo isor($a, 'default', 'in_array', $allowed);

How should boolean expressions be written in PHP?

How should the following boolean expression be written in PHP:
$foo = "";
if($var==TRUE){
$foo = "bar";
}
or
if($var==TRUE){
$foo = "bar";
}else{
$foo = "";
}
or
$foo = ($var==TRUE) ? "bar": "";
First off, true is not a constant, it's a token, so please don't uppercase it (I know some standards do that, but I think it confuses the meaning)...
Second, you don't need the redundant $var == true comparison inside the if. It's exactly the same as if ($var) { (For a double == comparison. An identical comparison === would need to be explicit).
Third, I prefer the pre-initialization. So:
$foo = '';
if ($var) {
$foo = 'one status';
} else {
$foo = 'another status';
}
If you don't need the else branch, just remove it. I prefer the pre-initialization since it forces you to initialize the variable, and it prevents cases where you forget to initialize it in one of the branches. Plus, it gives you a type hint when you go back to read the function later...
And for a simple branch like that, using the ternary syntax is fine. If there's more complex logic, I'd stay away though:
$foo = $var ? 'bar' : '';
All of those work. It's preference. I'd consider initializing the variable first like you do in the 1st example. But for something this simple, the 3rd option is fine in my book.
Also, the 3rd doesn't have to be so verbose if $var is just a boolean value:
$foo = $var ? "bar" : "";
I like the first one:
$foo = "";
if($var==TRUE){
$foo = "bar";
}
Since it is clear, concise, and easy to read.
I prefer the first one (except for the redundant test for the boolean) because it works consistently across languages, particularly those requiring to declare the variable (and maybe typify it) ahead of setting it.
Java:
String foo = "";
if (var) {
foo = "Something";
}
JavaScript or JavaFX:
var foo = "";
if (var) {
foo = "Something";
}
Etc.
One can use the 3rd form too but if the condition (or assignment) is complex, it is a bit less readable.
Doesn't matter very much. I like the first one when there's a lot of elseif's so that you know the variable is always initialized. But it's really just a matter of preference.
Like the quotes, I like using single ones in php. No good reason :)
The right answer, as it often is the case is, "it depends". In this case,
if ($var==TRUE) $foo = "bar";
else $foo = "";
is very clear. But what is your context?
In general, the tertiary operator, your third option, should be used with extreme caution, as it very easily becomes hard to read.
But think in terms of what you want your code to MEAN, more than about what it DOES. Do you want to set your $foo to a "normal" value and then override it? Or do you want to set to something that depends on what $var is?
Something I find useful to change, that is not directly what you ask, but that is similar, is this, from
function func() {
...
if ($condition) {
do plenty
of things
}
else {
do plenty
of things
}
}
That, I generally like to change to:
function func() {
...
if ($condition) {
do plenty
of things
return;
}
do plenty
of things
}
It generally makes sense.
Just ask yourself: "If someone who didn't know anything about my code read it, would it make sense to him? Or her?"

Categories