Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: What is the meaning of the syntax using the word 'and'?

Tags:

syntax

php

I'm working on making a walker in Wordpress. I saw some example code and it had the following syntax on one of it's lines:

!empty($item->attr_title)
and $attributes .= ' title="'.esc_attr($item->attr_title).'"';

What does this do? I would assume that if the object attributes are not empty it appends the title string, but I'm not sure the role of the "and" word here.

like image 216
Mentat Avatar asked Dec 06 '25 03:12

Mentat


2 Answers

PHP does short circuit evaluation of boolean expressions, that is, only as many terms are evaluated until the result is definite.

true and something()

will evaluate something() (the complete expression could still eval to false), whereas

false and something()

will stop evaluating after the false term.

like image 136
knittl Avatar answered Dec 08 '25 17:12

knittl


That's a shorthand for:

if (!empty($item->attr_title)) {
   $attributes .= ' title="'.esc_attr($item->attr_title).'"';
}
like image 36
Yang Avatar answered Dec 08 '25 16:12

Yang