Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isset()/Empty(), Arrays and Ternary Operator [duplicate]

Tags:

var

php

isset

We've all encountered it before, needing to print a variable in an input field but not knowing for sure whether the var is set, like this. Basically this is to avoid an e_warning.

<input value='<?php if(isset($var)){print($var);}; ?>'>

How can I write this shorter? I'm okay introducing a new function like this:

<input value='<?php printvar('myvar'); ?>'>

But I don't succeed in writing the printvar() function.

like image 254
bart Avatar asked Apr 29 '11 19:04

bart


People also ask

What is if isset ($_ GET?

The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.

Does Isset check for empty?

The empty() function is an inbuilt function in PHP that is used to check whether a variable is empty or not. The isset() function will generate a warning or e-notice when the variable does not exists. The empty() function will not generate any warning or e-notice when the variable does not exists.

How use isset with ternary operator in PHP?

"default-value"; // which is synonymous to: $var = isset($array["key"]) ? $array["key"] : "default-value"; In PHP 5.3+, if all you are checking on is a "truthy" value, you can use the "Elvis operator" (note that this does not check isset).


4 Answers

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');
like image 192
NikiC Avatar answered Oct 09 '22 19:10

NikiC


Another option:

<input value="<?php echo isset($var) ? $var : '' ?>">
like image 36
Galen Avatar answered Oct 09 '22 20:10

Galen


<input value='<?php @print($var); ?>'>
like image 44
arychj Avatar answered Oct 09 '22 20:10

arychj


The shortest answer I can come up with is <?php isset($var) AND print($var); ?>

Further details are here on php manual.

A simple alternative to an if statement, which is almost like a ternary operator, is the use of AND. Consider the following:

'; // This is an alternative isset( $value ) AND print( $value ); ?>

This does not work with echo() for some reason. I find this extremely useful!

like image 45
McAngujo Avatar answered Oct 09 '22 18:10

McAngujo