Today we’ll talk about what PHP expressions are. Expression in the PHP language is generally any string, number, object, array, or something else that is presented in explicit form or in the form of any calculations. For example:
'line with spaces' 7 2 + 2 5 / 2
All of the above are expressions. In this case, the expression must have some value. For the examples above, this is, for example, a line with text, an integer 7, an integer 4, and finally a fractional number 2.5.
As you can imagine, expressions themselves are useless until they are used. The whole charm of PHP is that it can be embedded in HTML.
I hope everyone knows what HTML is and know how to work with it. So, PHP can be embedded directly into HTML.
Let’s edit our index.php file. Enter the following code into:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>An example of embedding PHP in HTML</title> </head> <body> <h1>An example of embedding PHP in HTML</h1> 2 + 2 = <?php echo 2 + 2; ?> </body> </html>
and look at the result in the browser:
2 + 2 = 4
As we can see, the part of the code that was inside the <?php … ?> was successfully executed. If we now look at the source code of the page in the browser, we will only see the result.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>An example of embedding PHP in HTML</title> </head> <body> <h1>An example of embedding PHP in HTML</h1> 2 + 2 = 4 </body> </html>
Once again, the PHP code is executed on the server side. In the browser, the client is given only the result. I hope this is clear.
Now let’s see how it works. The web server sees that a file with the .php extension has been requested.
Server understands that there will be code in the PHP language, and transfers the contents of the file to the language interpreter. Interpreter knows that the code is located between the <?php and ?> and as soon as program meets them, then code executes. After that, it gives the result of the execution to the web server, and gives the result to the browser.
An expression, as we have already said, can be represented in the form of calculations. For calculations, in turn, several operators can be used.
We will talk about this in the next lesson.