Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding PHP & (ampersand, bitwise and) operator

I often use ($var & 1) in my code, which returns true if $var is an odd number and false if it's an even number.

But what does "&" actually do?

like image 712
ryonlife Avatar asked Mar 01 '09 18:03

ryonlife


People also ask

Is PHP easy to understand?

PHP is an easy language to grasp, and it's a great start before you dive into more complex web languages like HTML,CSS, SQL, and JavaScript. If you're learning WordPress too, keep an eye on what people are using with it.

What is PHP actually used for?

PHP (Hypertext Preprocessor) is known as a general-purpose scripting language that can be used to develop dynamic and interactive websites. It was among the first server-side languages that could be embedded into HTML, making it easier to add functionality to web pages without needing to call external files for data.

What is PHP in simple words?

(PHP: Hypertext Preprocessor) An extremely popular scripting language that is used to create dynamic Web pages. Combining syntax from the C, Java and Perl languages, PHP code is embedded within HTML pages for server side execution.


1 Answers

& is binary and. If you have a binary value, and you and with another binary value, then the result will be the bitwise and of the two. An example:

  01101010 & 01011001 = 01001000 

The rightmost bit is either a 1 (and in that case the number is an odd number) or it is a 0, in which case the number is even. If you & a number with 1, you only look at the least significant bit, and the if checks if the number is a 1 or a 0. As others have mentioned, look at the bitwise operators for info on how they work.

like image 187
Marius Avatar answered Sep 23 '22 07:09

Marius