fightstarr20
fightstarr20

Reputation: 12598

PHP null coalescing operator confusion - how to use in an if statement?

I usually do this in PHP to handle post parameters...

if (isset($_POST['name'])) {

    echo 'This is the post section';
    echo 'Output Attributes';
    echo $attribute1
    echo $attribute2

} else {

    echo 'The post is empty';

}

In an attempt to simplyfy things I am trying to use the null coalescing operator but I am slightly confused. uising an exmample I have this..

$name = $_POST['name'] ?? 'The post is empty';

But how do I get this to act like an if statement so I can output different sections for example?

Upvotes: 0

Views: 177

Answers (2)

symlink
symlink

Reputation: 12209

This:

$name = $_POST['name'] ?? 'The post is empty';

is equivalent to this:

if(isset($_POST['name'])){
  $name = $_POST['name'];
}else{
  $name = 'The post is empty';
}

If you want to do anything more complicated than that, you have to go with your own if/else statement.

Upvotes: 2

dipser
dipser

Reputation: 442

I think it depends. One way would be:

<?php if ( $_POST['name'] ?? false ) {  } else {} ?>

The operator is cool, but it can't do everything. And here it doesn't make it better.

Upvotes: 1

Related Questions