February 6th 2007
(1) PHP Lesson 2
Educational, Programming, Tutorials
In a previous post I started you off on the basics of PHP and you managed to get Hello World! displayed on the screen. This lesson we are going to learn about how to create, use and manage variables. Hope you enjoy it…
Lesson 2: Variables
Unlike programming languages such as C++, in PHP you don’t have to state what type of variable you’re creating when you create one. A variable such as $myvar could just as well be a number as it could be a word. It’s as easy as pie to create different variables:
<?php
$age = 15;
$name = "John";
?>
Here we created 2 variables: $age and $name which values’ are 15 and ‘John’ respectively. It’s that easy to create variables. Now that we have created variables we can manipulate them. Say for example we wanted to increase the $age variable and assign the new value to $age again, this is what we would add before the end of the script:
$age = $age+1;
If we now output the $age variable we would find that it displays 16 and not 15.
echo $age; //this would display ‘15′
We can also attach strings together. Take the $name variable we created earlier. We can take that and also create a last name in a different variable and then string them together to make the $name variable include the first and last name. Here we go:
$lastname = "Smith";
$fullname = $name.$lastname; //this would create “JohnSmith”
$fullname = $name.” “.$lastname; //this would create “John Smith”
So, let’s try and put this all together and make a useful program out of it. Here we manipulate the age by turning it into dog years. We also here string the first and last names together and then as a step towards the next lesson we’ll count the number of characters in the names.
<?php
$age = 15;
$firstname = "John";
$lastname = "Smith";
$i = 0; //used later on as a counter
$dog = $age*7;
echo “You’re “.$age.” human years old and “.$dog.” dog years!”;
echo “<br />”; //create a new line; just regular html
$name = $firstname.” “.$lastname;
$i = $i + strlen($firstname); //0 + 4
$i = $i + strlen($lastname); //4 + 5
echo $name.”, you have “.$i.” letters in your name!”;
?>
Try it out and play around with it! Next lesson we’re going to look at some of the functions we can apply to strings such as getting the length of the string and searching for a specific item within a variable.
/images/9r_leaf.png)