PHP grammar that came out in practice and was a little confusing

Sep 9, 2020 PHP beginner

#Introduction I have been working as a web engineer at a company in Tokyo since August 2020.

The development environment is so-called full scratch PHP, I was from a programming school that mainly studies Ruby, so I had hardly touched PHP before joining the company.

It’s been about a month since I joined the company, and now I understand the basic grammar, and while researching new functions I encounter each time We are repairing the existing system.

During such work, I saw a description that was particularly uncomfortable. I will leave it on Qiita so that I will not forget it soon.

#Problem code

isset ($ _REQUEST ['search']) && $ var = $ _REQUEST ['search'];

It’s a normal code, but it was confusing when I saw it.


Until now when using isset ()

if (isset ($ _ REQUEST ['search'])) {
  $ var = $ _REQUEST ['search'];
}

I was used to seeing patterns like ↑ The logical operator && only had the image used as a condition for AND.
Meanwhile, the code of the problem I encountered

isset ($ _REQUEST ['search']) && $ var = $ _REQUEST ['search'];

Wai at first sight “What is AND?” I rolled it up in my heart.

I investigated how it works, but only examples of conditional branching in if statements. After all, I couldn’t find a critical answer right away, so I asked my seniors a question.

#After all I was told that if isset () on the left side is true, the assignment on the right side will be performed. I feel that doing something like an if statement is almost the same, but under simple conditions like this one, it’s a one-liner and easy-to-read writing style.

Try using paiza.io I tried running the following code

$ str ='Hello!';
isset ($ str) && $ var = $ str;

echo $ var;


result Image from Gyazo ** and ↑

It seems that this kind of writing is sometimes found in languages other than PHP.

#Summary If readability is improved, write a one-liner description like this one. I will also use it positively.

I haven’t joined the company yet, but the code I touch in practice is fun. I’m going to spend my days immersed in PHP for a while.