6

I want to get a value from the session, but use a default if it is not defined. And ofcourse I want to circumvent the PHP notice.

You can write a function that does this

function get(&$var, $default){
    if(isset($var)) return $var;
    return $default;
}

echo get($foo, "bar\n");
$foobar = "foobar";
echo get($foobar, "ERROR");

Example in action

Is there a way to do this without defining this function in every file?

6 Answers 6

10

You can define it in one script and then require_once that script in your other scripts

You could also just use the ternary operator:

$myVar = isset($var)?$var:$default;
Sign up to request clarification or add additional context in comments.

4 Comments

Yeah -- are you intending to add it to the language?
That is not possible (for me) ofcourse, but I thought there might be a language built-in alternative
Well you can include the same script in several different projects. I might be missing the spirit of the question here, though.
What about the ternary operator? I just added an example to my answer.
8

From PHP 7, you can now use the null coalescing operator :

$var ?? $default

that does exactly like your function

Comments

4

Use this concise alternative:

isset($myVar) || $myvar=$default;

The || operator is short circuit, it will not evaluate second operant if the first one be evaluated true.

1 Comment

Please include an explanation of why you think your code solves the problem.
1

The Null coalescing operator has been added to PHP version 7.0, what it does is replaces

$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

with a shorter version:

$username = $_GET['user'] ?? 'nobody';

What the line above does, is check if $_GET['user'] is set, and not null, then it will assign that to the $username variable, if $_GET['user'] is not set (and thus null) it will default to the 'nobody' string so $username is nobody.

Your code should look like:

echo $foo ?? "bar\n";
$foobar = "foobar";
echo $foobar ?? "ERROR";

Comments

0

Use less code to do what you need.

You don't need to specify the variable again using the _?_:_ format.

echo $var?:"default";

Is the same as

echo $var?$var:"default";

Now as far as an empty check, you could use @ to mute notices, I'm not sure of the technical ramifications, but you're already doing your own checking while using this format:

echo @$non_existing_var?:"default";

Some examples:

<?php

    $nope = null;
    $yup = "hello";
    echo ($nope?:$yup) . "\n" ;
    echo ($yup?:$nope)  . "\n" ;

    $items = [ 'one', 'two', false, 'three', 'four', null ];

    foreach($items as $item):
        echo($item?:"default shown (".var_export($item,true).")")."\n";
    endforeach;

    echo(@$non_existing?:"default for non-existant variable!");

?>

Output:

$ php variabledefault.php
 hello
 hello
 one
 two
 default shown (false)
 three
 four
 default shown (NULL)
 default for non-existant variable!%                                                                                                                   

3 Comments

This is incorrect: $v=false; echo $v?:"not set"; will incorrectly yield "not set"
Yes, so it is not the answer to the question. The question was "Show a default if the variable is not set", not "Show a specified value if the variable evaluates to false"
"I want to get a value from the session, but use a default if it is not defined. And ofcourse I want to circumvent the PHP notice." This can be achieved exactly as requested by using (if the 'derp' session variable is not set): print @$_SESSION['derp']?:"default"; That said, yes, if it's false, it will return the default, but that's how logic works.
0

You could use my tiny library ValueResolver in this case, for example:

$myVar = ValueResolver::resolve($var, $default);

and don't forget to use namespace use LapaLabs\ValueResolver\Resolver\ValueResolver;

There are also ability to typecasting, for example if your variable's value should be integer, so use this:

$id = ValueResolver::toInteger('6 apples', 1); // returns 6
$id = ValueResolver::toInteger('There are no apples', 1); // returns 1 (used default value)

Check the docs for more examples

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.