PHP interview questions: $ a + $ a ++ and $ a + $ a ++

Source: Internet
Author: User
The results of $ a + $ a ++ and $ a + $ a ++ are almost always wrong for many programmers, so what is the final result of $ a + $ a ++ and $ a + $ a ++? Let's take a look. let's take a look... the results of $ a + $ a ++ and $ a + $ a ++ are almost always wrong for many programmers, so what is the final result of $ a + $ a ++ and $ a + $ a ++? Let's take a look.

Let's take a look at the question:

$ A = 1;

$ B = $ a + $ a ++; // Result: $ a = 2, $ B = 3

This question is not very difficult. Obviously, the priority of ++ in PHP is higher than that of ++. Therefore, execute $ a ++ first. then, the value of $ a is 2.

Next question:

$ A = 1;

$ B = $ a + $ a ++;

What is the value of $ B? The answer is: 3.

Why is it 3? Isn't it higher than ++'s priority? After $ a ++ is executed, the value of $ a should be 2 and the result is 5. in fact, this is the correct answer: 3. at first, I thought it should be 5.

Explanation:Operators are combined from the left to the right. the above expression is equivalent

$ = ($ A + $ a) + $ a ++

Based on the left-hand combination principle:

// Calculate $ a + $ a $ B = 2 + $ a ++ first; // at this time, we need to compare the operator priorities of ++ and ++. $ B = 2 + 1; // $ a = 2

This is a tough PHP pen question. brackets should be used in the actual project code to avoid these problems.



Article URL:

Reprint ^ at will, but please attach the tutorial address.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.