What will be the output of the following PHP code: echo 5 + "10 apples";?

Prepare for the Zend Certified PHP Engineer Exam with our comprehensive test, featuring flashcards and multiple choice questions. Each question comes with detailed hints and explanations. Ensure you're ready for your exam!

The output of the code echo 5 + "10 apples"; is indeed 15. This result is due to how PHP handles the addition operation when one of the operands is a string that contains numeric characters and additional non-numeric characters.

When the addition operator + is used, PHP attempts to convert the string to a number. In this case, the string "10 apples" begins with the digits '10', which PHP successfully converts to the integer value 10. The operation then performs the addition: 5 (the integer on the left) plus 10 (the converted value from the string) results in 15.

The non-numeric portion of the string, "apples", is ignored in this operation as PHP primarily focuses on the numeric part at the beginning of the string. Therefore, the final output is simply the numeric result of the addition, which is 15.

This behavior is consistent with PHP's type juggling feature, where the language attempts to convert between types as needed during operations like arithmetic.

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy