What Is the PHP Shorthand For: Print Var If Var Exist

What is the PHP shorthand for: print var if var exist

For PHP >= 7.0:

As of PHP 7 you can use the null-coalesce operator:

$user = $_GET['user'] ?? 'guest';

Or in your usage:

<?= $myVar ?? '' ?>

For PHP >= 5.x:

My recommendation would be to create a issetor function:

function issetor(&$var, $default = null) {
return isset($var) ? $var : $default;
}

This takes a variable as argument and returns it, if it exists, or a default value, if it doesn't. Now you can do:

echo issetor($myVar);

But also use it in other cases:

$user = issetor($_GET['user'], 'guest');

Is there PHP shorthand for : if (a) {var = a}

No such shorthand exists. However you can accomplish the same thing like this:

$var = $a;
if (!$var) {
unset($var);
}

If $var is falsey (0, "0", "", null, empty, or false) it will be unset as if it had not been instantiated in the first place.

Edit:

unset also works on array indexes such as the following:

unset($var['a']);

The above wouldn't just set the value to null. It would set it to null and remove it from the array.

What you probably want is something like this:

$temp = $a;
if ($temp) {
$array['a'] = $temp;
}
else {
unset($temp);
}

You can also accomplish what you desire with a function:

function add_value_if_exists(&$array, $key, $value) {
if ($value) {
$array[$key] = $value;
}
}

add_value_if_exists($array, 'a', $a);

In the above $array will only be modified if $a is truthy.

PHP shorthand for isset()?

Update for PHP 7 (thanks shock_gone_wild)

PHP 7 introduces the null coalescing operator which simplifies the below statements to:

$var = $var ?? "default";

Before PHP 7

No, there is no special operator or special syntax for this. However, you could use the ternary operator:

$var = isset($var) ? $var : "default";

Or like this:

isset($var) ?: $var = 'default';

shorthand if explanation ? mark operator

The line $someVariable = $condition ? $valueA : $valueB is equivalent to:

if ( $condition ) {
$someVariable = $valueA;
}
else {
$someVariable = $valueB;
}

So, basically, if the condition is TRUE, $someVariable will take the first value after the ? symbol. If FALSE, it will take the second value (the one after the : symbol).

There's a special case where you can not define the first value and it is like this: $someVariable = $someValue ?: $someOtherValue. It's equivalent to:

if ( $someValue ) {
$someVariable = $someValue;
}
else {
$someVariable = $someOtherValue;
}

So, if $someValue evaluates to TRUE (any value different than 0 is evaluated to TRUE), then $someVariable will catch that value. Otherwise, it will catch $someOtherValue.

To give you an example:

function printGender( $gender ) {
echo "The user's gender is: " . ( $gender == 0 ? "Male" : "Female" );
}

printGender(0); // Will print "The user's gender is: Male"
printGender(1); // Will print "The user's gender is: Female"

Another example:

function printValuesStrictlyDifferentThanZero( $value ) {
echo "Value: " . ( $value ?: 1 );
}

printValuesStrictlyDifferentThanZero(0); // $value evaluates to FALSE, so it echoes 1
printValuesStrictlyDifferentThanZero(1); // $value evaluates to TRUE, so it echoes that $value

EDIT:

The operator ?: is NOT called the ternary operator. There are multiple ways to define a ternary operator (an operator that takes three operands). It is a ternary operator, but not the ternary operator. Some people just call it the ternary operator because they're used to do it and, probably, it's the only ternary operator vastly known in PHP, but a ternary operator is way more general than that.

It's name is the conditional operator or, more strictly, the ternary conditional operator.

Let's suppose I define a new operator called log base that evaluates, inline, if the logarithm of a number $A with base $C equals to $B, with its syntax like $correct = $A log $B base $C and it returns TRUE if the logarithm is right, or FALSE if it's not.

Of course that operation is hypothetical, but it is a ternary operator, just like ?:. I'm gonna call it the logarithm checker operator.

Short if this else that in PHP?

$myVariable ? $myVariable : ""; 

is equivalent to:

$myVariable ?: "";

PS: You should be aware that PHP does type juggling here. This is basically the same as:

if ($myVariable == TRUE) ...

If $myVariable happens to be a string like 0, it will evaluate to false. However 00 will evaluate to true. I've found this not so useful as it appears to be. In many cases you will need to check if $myVariable is set first, or do a type comparison and make sure the variable is boolean...

PHP: Check if variable exist but also if has a value equal to something

Sadly that's the only way to do it. But there are approaches for dealing with larger arrays. For instance something like this:

$required = array('myvar', 'foo', 'bar', 'baz');
$missing = array_diff($required, array_keys($_GET));

The variable $missing now contains a list of values that are required, but missing from the $_GET array. You can use the $missing array to display a message to the visitor.

Or you can use something like that:

$required = array('myvar', 'foo', 'bar', 'baz');
$missing = array_diff($required, array_keys($_GET));
foreach($missing as $m ) {
$_GET[$m] = null;
}

Now each required element at least has a default value. You can now use if($_GET['myvar'] == 'something') without worrying that the key isn't set.

Update

One other way to clean up the code would be using a function that checks if the value is set.

function getValue($key) {
if (!isset($_GET[$key])) {
return false;
}
return $_GET[$key];
}

if (getValue('myvar') == 'something') {
// Do something
}

Overview of PHP shorthand

Here are some of the shorthand operators used in PHP.

//If $y > 10, $x will say 'foo', else it'll say 'bar'
$x = ($y > 10) ? 'foo' : 'bar';

//Short way of saying <? print $foo;?>, useful in HTML templates
<?=$foo?>

//Shorthand way of doing the for loop, useful in html templates
for ($x=1; $x < 100; $x++):
//Do something
end for;

//Shorthand way of the foreach loop
foreach ($array as $key=>$value):
//Do something;
endforeach;

//Another way of If/else:
if ($x > 10):
doX();
doY();
doZ();
else:
doA();
doB();
endif;

//You can also do an if statement without any brackets or colons if you only need to
//execute one statement after your if:

if ($x = 100)
doX();
$x = 1000;

// PHP 5.4 introduced an array shorthand

$a = [1, 2, 3, 4];
$b = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4];


Related Topics



Leave a reply



Submit