$arr =array(); foreach ($cur_news_list as $news){ empty($arr[$news['id']]) && ($arr[$news]['id'] = array()); $arr[$news[id]][] = &$news; } 

What happens in the third line?

 empty($arr[$news['id']]) && ($arr[$news]['id'] = array()); 
  • If $arr =array(); is determined immediately before the required line, the first condition on this line makes no sense, because will always return false. Therefore, the second part of the condition - assignment - will always be fulfilled. And to the question "what is happening," in this context, we can say that the "Hindu code" is happening. - uorypm

2 answers 2

Assign a value if not specified.
If rewritten with if will

 if (empty($arr[$news['id']]) { $arr[$news]['id'] = array(); } 

PS: It seems that in the line $arr[$news]['id'] = array(); error - key to empty($arr[$news['id']] does not match the key with the right.
Probably need $arr[$news['id']] = array();

  • yes there is an error .. - baneling

This trick is connected with the peculiarity of calculating the operands of the operations && (logical AND) and || (logical OR).

PHP, like a number of other programming languages, can optimize code when calculating the results of logical operations. At the same time, he uses the following rules:

  1. If the first operand of the && operator is (or is reduced to) false , then the second operand is not evaluated , since the result of the expression will still be equal to false .
  2. If the first operand of the operator || equal to (or given to) true , then the second operand is not calculated , since the result of the expression will still be equal to true .

In this case, if the operand includes a function that has side effects, then such a trick can be used as an alternative to the if construct.

A typical example that occurred 10 years ago in every second PHP application looked like this:

 $link = mysql_connect('...') or die('Cannot connect'); 

If we rewrite this code using if , we get:

 $link = mysql_connect('...'); if (!$link) { die('Cannot connect') } 

Despite some abbreviation of the code, I would not recommend you to use a similar trick in real applications. Not always he allows to make the code more readable. (The same, incidentally, applies to assignment in conditions.)


Now a few words about your particular case. Code

 empty($arr[$news['id']]) && ($arr[$news]['id'] = array()); 

PHP will be understood as the following set of instructions:

 if (empty($arr[$news['id']])) { $arr[$news]['id'] = array(); }