12

Is there a concise way to check if a variable is set, and then echo it without repeating the same variable name?

Instead of this:

<?php
    if(!empty($this->variable)) {
        echo '<a href="', $this->variable, '">Link</a>';
    }
?>

I'm thinking about something in the lines of this C-style pseudocode:

<?php
    echo if(!empty($this->variable, '<a href="', %s, '">Link</a>'));
?>

PHP has sprintf, but it doesn't quite do what I was hoping for. If course I could make a method/function out of it, but surely there must be a way to do it "natively"?

Update: Ternary operations would also repeat the $this->variable part, if I understood it?

echo (!empty($this->variable) ? '<a href="',$this->variable,'">Link</a> : "nothing");
2
  • I'm not aware of any shorthand for that. If you use it a lot, I would anyway recommend creating a function for that.
    – str
    Commented Apr 12, 2013 at 11:42
  • Ternary operation ((bool) ? value : default ) is not an option?
    – BlitZ
    Commented Apr 12, 2013 at 11:42

3 Answers 3

19

The closest you can get to what you are looking for is using short form of ternary operator (available since PHP5.3)

echo $a ?: "not set"; // will print $a if $a evaluates to `true` or "not set" if not

But this will trigger "Undefined variable" notice. Which you can obviously suppress with @

echo @$a ?: "not set";

Still, not the most elegant/clean solution.

So, the cleanest code you can hope for is

echo isset($a) ? $a: '';
2
  • 1
    Often I'll use a technique similar to this but with empty which also accounts for empty strings
    – christian
    Commented Dec 2, 2014 at 15:59
  • Good thinking. Shame there isn't an inbuilt PHP function and surprising too. Commented Feb 27, 2018 at 19:20
17

Update:

PHP 7 introduces a new feature: Null coalescing operator

Here is the example from php.net.

<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>

For those not using PHP7 yet here is my original answer...

I use a small function to achieve this:

function ifset(&$var, $else = '') {
  return isset($var) && $var ? $var : $else;
}

Example:

$a = 'potato';

echo ifset($a);           // outputs 'potato'
echo ifset($a, 'carrot'); // outputs 'potato'
echo ifset($b);           // outputs nothing
echo ifset($b, 'carrot'); // outputs 'carrot'

Caveat: As Inigo pointed out in a comment below one undesirable side effect of using this function is that it can modify the object / array that you are inspecting. For example:

$fruits = new stdClass;
$fruits->lemon = 'sour';
echo ifset($fruits->peach);
var_dump($fruits);

Will output:

(object) array(
  'lemon' => 'sour',
  'peach' => NULL,
)
2
  • 2
    I thought of this as well. However, the following problem arises: $data = []; $data['a'] = 2; echo ifset($data['b']); var_dump($data); Will return array(2) { ["a"]=> int(2) ["b"]=> NULL }. So the ifset function actually modifies the original data object...
    – Inigo
    Commented Jul 7, 2016 at 10:51
  • 1
    You are totally right Inigo - I'd never realised that as don't usually use this with arrays. Looks like we'll have to wait till we are using PHP7 for a solution that definitely doesn't modify the original object.
    – Felix Eve
    Commented Jul 8, 2016 at 3:59
-1

Use isset function of php like this:

<?php

  echo $result = isset($this->variable) ? $this->variable : "variable not set";

 ?>

i think this will help.

1
  • 1
    The $this->variable would still repeat in the "do something" part. I'd like to do it without repeating it multiple times in the command. (downvote wasn't mine...) Commented Apr 12, 2013 at 11:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.