Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 605
bart Avatar asked Apr 29 '11 19:04

bart


People also ask

What is $_ GET in PHP?

PHP $_GET is a PHP super global variable which is used to collect form data after submitting an HTML form with method="get". $_GET can also collect data sent in the URL. Assume we have an HTML page that contains a hyperlink with parameters: <html> <body>

What does ?: Mean in PHP?

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.

Does variable exist PHP?

PHP isset() FunctionThe 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.

What is $$ VAR?

$$var: $$var stores the value of $variable inside it. Syntax: $variable = "value"; $$variable = "new_value"; $variable is the initial variable with the value. $$variable is used to hold another value.


2 Answers

For PHP >= 5.x:

My recommendation would be to create a issetor function:

function issetor(&$var, $default = false) {     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'); 

For PHP >= 7.0:

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

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

Or in your usage:

<?= $myVar ?? '' ?> 
like image 143
NikiC Avatar answered Oct 08 '22 16:10

NikiC


Another option:

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

Galen