0% found this document useful (0 votes)
118 views

PHP Tags

The document discusses various PHP tags that can be used to embed PHP code in HTML documents. It explains that only code between PHP tags will be interpreted, while the rest is ignored. It describes the most common PHP tags (<?php ?> and <script language="php">) as well as shorter alternatives (<? ?> and <% %>) that may not be supported on all servers. The document also discusses mixing PHP and HTML, including jumping in and out of PHP code to output HTML, and using conditional PHP blocks within HTML.

Uploaded by

bing
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
118 views

PHP Tags

The document discusses various PHP tags that can be used to embed PHP code in HTML documents. It explains that only code between PHP tags will be interpreted, while the rest is ignored. It describes the most common PHP tags (<?php ?> and <script language="php">) as well as shorter alternatives (<? ?> and <% %>) that may not be supported on all servers. The document also discusses mixing PHP and HTML, including jumping in and out of PHP code to output HTML, and using conditional PHP blocks within HTML.

Uploaded by

bing
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

PHP TAGS

In the last chapter, we used those magic PHP tags. You may save your files with the .php extension, but that's
not enough. Sure, when you use the appropriate extension, as defined in the config file of the webserver, PHP
will look at the file. But only the stuff between the PHP tags are actually interpreted - the rest is just ignored.
This allows you to mix HTML and PHP in the same file, and while other technologies like ASP.NET tries to
separate code and markup, PHP still encourages this mix, and allows you to do it in several different ways.
In the previous chapter, we used the most common and most correct way of starting the PHP block:
<?php [code here] ?>
Another version is this one, which is the same kind of tags used for e.g. blocks of JavaScript code:
<script language="php"> [code here] </script>
Those two options are always available. However, a lot of PHP installations are set up to allow the short
version as well:
<? [code here] ?>
On some servers, ASP style tags have been enabled. They look like this:
<% [code here] %>
Since this is not necessarily supported on all servers, you may wish to use the full version instead.
The same goes for the special output version, which looks like this:
<?= [output here] ?>
The last one is the same as writing:
<?php echo "some output"; ?>
As you can see, you do save some keystrokes, and if you're writing code for your self only, you may be
tempted to use the short versions instead. Just be aware that if you ever change to another server, the last two
options may be disabled.

In and out of PHP


When writing webpages, you naturally use HTML all over the place. You will quickly need to combine HTML
tags with output generated from PHP. Now that's easy:
<?php
$myVar = "Hello world!";
echo "<b>" . $myVar . "</b>";
?>

We simply create a string consisting of three parts: The starting bold tag, our variable, and then the ending bold
tag. Using the dot operator, which concatenates strings in PHP, we output the entire thing as if it was just
another piece of text. In simple cases like this one, our above example is just fine. However, if you suddenly
start having way more plain HTML, with a minimum of PHP code required in it, the above approach is actually
not the best way to go. You may do it like this instead:
<?php
$myVar = "Hello world!";
?>

<i>We have HTML <u>all</u> over the place here!</i><br />


<i>But some PHP as well, as you can see:</i><br />
A message from PHP: <b><?php echo $myVar; ?></b>

In this tiny example, we have way more plain HTML and text than we have PHP code. It makes sense to jump
out of PHP in those cases, and according to the PHP manual, it even offers better performance than outputting
huge amounts of HTML through PHP. So we can jump out of it, but can we jump in again? Of course. And PHP
is actually quite flexible in this area, as the following example will show you:
<?php
$myVar = 42;
if($myVar == 42)
{
?>
<b>Yes, the number is in fact 42!</b>
<?php
}
?>

As you can see, we jump out of PHP in the middle of a conditional block of code. PHP understands this just
fine. The HTML and text part is only outputted if $myVar is actually set to 42. Try changing it and you will see
that PHP respects the condition even when you mix in plain HTML and text.

VARIABLES
Variables are one of the most important aspects of every programming language. They allow you to store a
value within a named container, for later use or manipulation. Storing and retrieving something from memory is
a complicated task, but fortunately, PHP hides all this low level stuff, and makes it super easy to declare and
use variables.
In PHP, variables can be recognized from the $ in front of them. The dollar sign is used to inform PHP that the
following piece of text refers to a variable. If you have used other programming languages, you may be used to
telling the compiler/interpreter which type of variable you wish to declare. However, PHP is a so-called loosely
typed language. It means that you don't have to declare a variable as a specific type - it's type will be
determined by what you put into it. We will talk more about this in the next chapter. For now, let's work with
some variables.
In many other languages, you have to declare a variable before using it, usually with a specific keyword like
"var", "dim" or at least the type you wish to use for the variable. But not so with PHP. Just enter the name of it
and assign a value, and you're good to go. Here is an example:
<?php
$myVar = "Hello world!";
?>

Now that's pretty simple! You simply write the name of the variable with a dollar sign in front of it, an equal sign,
and then you tell PHP what to put inside of the variable. Now, the variable called myVar holds the value of a
text string - "Hello world!". Using the variable is even simpler. In this example, we use it with the echo function
(it's actually just a language construct and not a function, but that doesn't matter now), which simply outputs it.
<?php
$myVar = "Hello world!";
echo $myVar;
?>

In this example, we used a text string, but we may as well use e.g. a number, like this:
<?php

$myVar = 42;
echo $myVar;
?>

On the other hand, why not just use a text string with the number 42 in it? That's no problem. Try putting quotes
around the number in the above example, and you will see that you get the exact same output. But is it in fact
the same? No, of course not. While PHP may not seem to care, internally it does, keeping track of the data
types you put into your variables. You can read

One of the single most important statements in every programming language is the "if" statement. Being able to
set up conditional blocks of code is a fundamental principal of writing software. If you have already used
another programming language, chances are that you can use the PHP if statement straight away, since it
looks pretty much the same as in other programming languages. If not, here are some examples to get you
started.
<?php
$number = 42;
if($number == 42)
echo "The number is 42!";
?>

It's very simple. We declare a variable called number and assign the value 42 to it. In the next line, we use the
if statement to check if the number is what we expect. The next line of code will only be executed if the
condition evaluates to true. If you change the number in the first line to something else, you will see that the
echo line is not executed.
As you can see, we are using two equal signs after each other - why is that? In PHP, and in many other
programming languages, a single equal sign is an assignment operator. It's used to assign a value to e.g. a
variable. Two equal signs are a comparison operator, that is, it's used to compare two values. So, in this case,
we use two equal signs to compare the two items: $number and 42. Had we only used one equal sign, 42
would be assigned to $number, and no comparison would have been made.
PHP actually takes it one step further, introducing the triple equal sign. The difference is if you use two equal
signs, PHP will only look to see if the values are identical. If you use three of them, PHP will compare both
value and type and only if both of them match, the expression is true. Here is an example to show you the
difference:
<?php
$number = 42;
if($number === "42")
echo "The number is 42!";
?>

All we did was compare the variable against a string containing "42" instead of the number 42. But now that we
use three equal signs, the types are no longer the same, since one is an integer and the other is a text string.
I'm sure that seems a bit complicated right now, but just try to remember it for now - in the beginning, the
double equal sign is pretty much all you need.

The else statement


If one of the ways is not good enough, why not go the other way? The else statement is the if statements best
friend - it's the alternative to a failed if statement. In code, it can look a bit like this:
<?php
$animal = "Cat";

if($animal == "Dog")
echo "It's a dog!";
else
echo "I'm sure it's some sort of animal, but not a dog!"
?>

Whenever the if statement doesn't evaluate to true, the else statement(s) are executed, if there are any. As you
saw in the first example, the else part is not required if you don't need it. In this case, we look for a certain
animal, the dog, and prints a status message depending on whether or not we found it. Try changing the
$animal variable between "Cat" and "Dog" to see the difference.
In this example, each conditional block only consists of one line of code. That's why we can leave out the curly
brackets. In a case where more than one line of code should be dependent of our if or else statement, they
should be surrounded by curly brackets, like this:
<?php
$animal = "Cat";
if($animal == "Dog")
echo "It's a dog!";
else
{
echo "I'm sure it's some sort of animal, but not a dog!";
echo "This line is still a part of the else statement.";
}
?>

Different operators
In the previous examples, we only used the equal operator to compare values. However, there are many more
operators. Each of them can be used instead of the equal operator, e.g. like this:
<?php
$number = 42;
if($number != 30)
echo "Hello World!";
?>

!= means "not equal to", the opposite of == (equal to)


if($number > 30)
Is $number bigger than 30?
if($number < 30)
Is $number smaller than 30?
if($number >= 30)
Is $number bigger than or equal to 30?
if($number <= 30)

Is $number smaller than or equal to 30?


Click through to the next chapter for more information about if statements.\
In this chapter, we will look at more ways of using the if statement and its related operators and structures.
Once you dig deeper into PHP, you will soon realize that it's a language with many alternative ways of doing
various things.
First of all, it's important to know how to treat an if statement with more than one condition. If statements can be
nested, like this:
<?php
$number = 10;
if($number > 0)
if($number < 20)
echo "Number is bigger than 0 but smaller than 20!";
?>

The echo line will only be executed if both if statements evaluates to true. However, the example could have
been written like this as well:
<?php
$number = 10;
if(($number > 0) and ($number < 20))
echo "Number is bigger than 0 but smaller than 20!";
?>

How you should write it depends on the situation and your personal preferences.
In the previous chapter, we looked at the else statement. PHP has another flavor of this, the elseif statement.
That's right, it's an if and an else statement in one. It can be used like this:
<?php
$number = 10;
if($number > 20)
echo "Number is bigger than 20!";
elseif($number > 10)
echo "Number is bigger than 10!";
else
echo "The number seems a bit low..."
?>

This is nothing but an alternative syntax. You may as well have written an else statement, followed by yet
another if statement.
Instead of using regular PHP blocks, surrounded with curly brackets, PHP supports an alternative syntax for its
control structures like if, while etc. It's not very commonly used, but here's an example anyway:
<?php
$number = 10;
if($number == 10):
echo "Number is 10!";

else:
echo "Number is not 10.. ";
echo "But why?";
endif;
?>

If you like this syntax better, you can use it - it doesn't make much of a difference.

The ternary operator


Sometimes, pulling out an entire if and else statement feels like a bit much. For instance, have a look at this
example, where we use an if statement to append the proper word to an output variable, based on whether or
not there are any items in our basket:
<?php
$numberOfItems = 2;
$output = "There is ";
if($numberOfItems > 0)
$output .= "something";
else
$output .= "nothing";
$output .= " in your basket";
echo $output;
?>

Using the ternary PHP operator, we could write this way shorter:
<?php
$numberOfItems = 0;
$output = "There is " . (($numberOfItems > 0) ? "something" : "nothing") . " in your
basket";
echo $output;
?>

This really brought down the number of code lines. The ternary operator is like a short version of an if-and-else
statement, all in one line. A condition inside a set of parentheses is the if statement. This is followed by a
question mark, and after that, the result if the condition is evaluated to true. Then we have a colon, followed by
the result if the condition is evaluated to false. To have all this inside the assignment line, we wrap it all inside a
set of parentheses, to tell PHP that this is actually one statement inside the line.
Whether you use this alternative syntax is once again up to you. In some cases it might make sense because
you're doing something really simple, while you may wish to stick to the long way of writing it in other cases, to
make your code more readable.
SWITCH STATEMENT
You can consider the switch statement as an alternative to several if statements, a control structure with a
range of options. For each option, you can define an action. Switch statements are great for choices with many
options, because they are easy to overview and modify to reflect changes in your situation.
The switch statement is built up around a condition, and then a number of case statements which can each
lead to an action. Here' s an example:
<?php
$answer = 0;

if(isset($_GET["answer"]))
$answer = $_GET["answer"];
switch($answer)
{
default:
echo "Which version of PHP are you using?<br /><br />";
echo "<a href=\"?answer=3\">3</a><br />";
echo "<a href=\"?answer=4\">4</a><br />";
echo "<a href=\"?answer=5\">5</a><br />";
break;
case 3:
echo "Ugh that's old, upgrade now!";
break;
case 4:
echo "Still on version 4? Give PHP 5 a try!";
break;
case 5:
echo "Good choice!";
break;
}
?>

The first couple of lines are used to retrieve an answer to our question from the query string - don't worry too
much about that right now, the $_GET and $_POST variables will be explained later on.
Then we get to the actual switch statement. It consists of the switch keyword and then the condition that we
want to evaluate. In our case, we use the $answer variable, which will hold a value passed through the query
string. Inside the switch statement, we start defining our case's. The first case is a bit special, because instead
of looking for a single value, we use the default keyword to define an action that will happen only if none of the
other cases matches. In our example, this allows us to output the question that we want to ask and then some
links for answering it. We ask the user which version of PHP they are using, and as soon as they click one of
the answer links, we will output an answer for them. If no answer is selected, or if an unknown answer is
entered through the query string, we simply output the question, since it's our default case.
Each case is built declared by using the case keyword, the value we wish to check for, a colon, the code we
wish to execute if we have the right case, and then the break statement to signal that if a case statement
matches, we want the switch statement to end.
This might seem a bit complicated, but try running the example and try the different options and you will soon
see that switch statements are pretty easy to work with.
Switch statements allows you to group several options into one case, and in PHP, you can test against strings
as well. Here's a small example:
$color = "red";
switch($color)
{
case "red":
case "blue":
case "green":

echo "Nice basic color!";


break;
case "black":
echo "Too dark!";
break;
case "white":
echo "Too bright!";
break;
}

You might also like