Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best hierarchical php syntax for assigning a variable to values if they are set

Tags:

variables

php

I want to do this for 5 sets of parameters is this the best way to do it or is there some simpler syntax?

if(isset($_GET['credentials'])) $credentials = $_GET['credentials'];
if(isset($_POST['credentials'])) $credentials = $_POST['credentials'];
if(isset($_POST['c'])) $credentials = $_POST['c'];
if(isset($_GET['c'])) $credentials = $_GET['c'];

Also with this same hierarchy.

like image 886
maxisme Avatar asked Feb 22 '18 20:02

maxisme


1 Answers

PHP 7 introduced the The null coalescing operator (??), which you can use like this:

$result = $var ?? 'default';

This will assign default to result if:

  • $var is undefined.
  • $var is NULL

You can also use multiple ?? operators:

$result = $null_var ?? $undefined_var ?? 'hello' ?? 'world'; // Result: hello

To answer your question, you should be doing something like:

$credentials = $_GET['c'] ?? $_POST['c'] ?? $_POST['credentials'] ?? $_GET['credentials'];

More details here and here

like image 110
Spoody Avatar answered Sep 28 '22 19:09

Spoody