Mattle Posted March 23, 2011 Posted March 23, 2011 (edited) Structure of PHP We have learned how we can parse some text to browser so far, the easiest thing in PHP. But wait, everything is easy, you only have to know how! PHP uses a if … else structure, similar like flash and Java. <?php if(1+2==3) { echo ‘Correct!’; } else { echo ‘Incorrect’; } ?>The example above shows a little math sum. I will explain every line.Line 1: We give the server the message that he is dealing with PHP code Line 2: We ask the question, if 1 + 2 = 3 execute the code surrounded by the first { }. Line 3: The code executed when the sum is correct. Line 4: End of the first block of code and then start a new one, a one which will be executed if the sum would be false. Line 5: The code executed when the sum is incorrect. Line 6: End of the second block of code. Line 7: End of the PHP code. In this example the browser always shows the text ”Correct!”, however, when we change the 3 into a 4, the browser will always give “Incorrect”. Variables In PHP you also have variables, thiny pieces of memory where you can store information or execute functions. These variables are indicated with the prefix $ (dollar sign). For example: <?php $name = ‘mattle’; ?>Bear in mind that text always need to stand between quotes. This script won’t do anything. So variables won’t be echoed by standard. But I can: <?php $name = ‘mattle’; echo $name; ?>Because we want to echo a variable we don’t need to place it between quotes. The variable itself is not a string. But what if I want to add some more text, like “Welcome, Mattias, enjoy your stay!”We could do it like this: <?php $name = ‘mattle’; echo ‘Welcome ’; echo $name; echo ‘, enjoy your stay!’; ?>That’s long. PHP knows some tricks to make from these 3 echo’s one echo. <?php $name = ‘mattle’; Echo ‘Welcome ’. $name . ‘, enjoy your stay!’; ?>What did we do? We've put two strings around the variable with on both sides 2 dots. In other words, we putted the variable out of the text. But you don’t have to close the echo with quotes. We simply can do this: <?php $name = ‘mattle’; echo ‘Welcome ’. $name; ?>Or this: <?php $name = ‘mattle’; echo $name . ‘, hi!’; ?>Thanks again for reading the second part of the multipart tutorial “First steps into PHP”.If you have comments, suggestions, don’t be shy and send me those. Happy trying Edited March 30, 2018 by Fearless Staff Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.