Archive for 'Basics'

Swishy Switch Statements

Posted on 25. Feb, 2010 by admin in Basics

Switch statements are very similar to if statements since both compare a condition and run code based on whether it is true or false. Unlike if statements which can be used to compare multiple variables and values, switch statements compare one variable  to a number of choices. Most likely you will use if statements to compare integers, and switch statements to compare strings.

Let’s go back to the same example we used for if statements to see how we complete an output for switch:


<?php
//Color of Stoplight
$stopLight = "Green";

//Switch statement
switch ($stopLight)
{
case "Red":
echo "Stop!";
break;

case "Yellow":
echo "Slow down...";
break;

case "Green":
echo "Floor it!";
break;
}

?>

Output:

Floor it!

There are several differences from our if statement syntax. The variable we want to test still goes inside the parentheses, but you do not put anything else. All the strings or numbers you want to compare it with go after case inside the {}. Notice also that you need to use break to end the code to run if the statement is true. Now, this is almost the same as our other if statement, but it is missing one thing. What happens if the light is not red, yellow, or green?


<?php
//Color of Stoplight
$stopLight = "Purple";

//Switch statement
switch ($stopLight)
{
case "Red":
echo "Stop!";
break;

case "Yellow":
echo "Slow down...";
break;

case "Green":
echo "Floor it!";
break;

default:
echo "The stoplight must be broken.";
break;

}

?>

Output:

The stoplight must be broken.

Just as we used the else statement to tell PHP what to do if none of the statements are true, we use the default statement in switch. As you can see, both can do the same thing, it is up to you to choose which one you want to use in your code.

Iffy If Statements

Posted on 25. Feb, 2010 by admin in Basics

For the next four tutorials we will be dealing with something called conditionals. No it is not something you wash your hair with… The definition of a conditional is “a statement that depends on a condition being true or false.” To help you understand stand this lets start out with an code example:


<?php
//Color of Stoplight
$stopLight = "Green";

//If statement
if($stopLight == "Red") {
echo "Stop!";
}
elseif($stopLight == "Yellow")    {
echo "Slow down...";
}
elseif($stopLight == "Green")    {
echo "Floor it!";
}
else     {
echo "The stoplight must be broken.";
}
?>

Output:

Floor it!

Lets break this down part by part. We are using a “function” called if, but instead of an argument we have a conditional in-between the parentheses.

The first if statement says, if $stopLight is equal to “Red” then it will run the code in the {} which prints out “Stop!” This is not true so it will not run the code. Instead, the function will go on to the next statement.

Each successive elseif statement is run if the previous elseif statement was false. If any of statements are true, it will run the code in the {} and skip down to the end } of the else statement.

The else statement is the code that runs if none of the statements are true. For example, if you put “Purple” as the stop light color it would run the code in-between the {} and print “The stoplight must be broken.”

Also when comparing numbers you can replace == with the following to find if numbers or greater than, less than, etc to each other:

  • ==     is equal to
  • !=     is not equal
  • <>     is not equal
  • >     is greater than
  • <     is less than
  • >=     is greater than or equal to
  • <=     is less than or equal to

Note: You may use as many if statements as you would like, but elseif and else statements must be accompanied by an if statement before it.

Silly Strings (Part 2)

Posted on 25. Feb, 2010 by admin in Basics

Ah, so you thought you were all done with strings, huh? Think again. You will spend a good deal of coding time in larger projects manipulating and otherwise dealing with strings. They will become even more important as we move on in our tutorials. Let’s just go over some useful functions when dealing with strings.

The function strlen() let’s us find the character length of a string. We use it by putting the variable or string literal in-between the parentheses, producing an integer answer.


<?php
echo strlen("I am the cookie monster!");
?>

Output:

24

This concept will come in handy later when we do loops and if statements. The next function of strpos() finds the position of a word in a string. Again, this will come in handy later. So, let’s say we wanted to find out what character position the word cookie was in the string “I am the cookie monster!” Our code would look something like this:


<?php
echo strpos("I am the cookie monster!", "cookie");
?>

Output:

8

If you count the number of character spaces you may be going, “Whoa that isn’t right. It should be nine!” My dear PHP friend you are wrong. It is eight because the first position is zero (the ‘I’), not one. Also notice the comma I put between the two string literals. The information we put between the parentheses of a function are called arguments. With a comma we can separate the two arguments we pass to this particular function. The first being the string to search for the word, and the second being the string we want to search it for. Similar to the following: “strpos(argument one, argument two);” Each function has its own arguments, so it is different for each one.

The last string function we will play with in this tutorial is the strrev() function. It’s job is to reverse a string. It’s mostly used to help us find patterns, for example a palindrome.


<?php
//Reverse this string
echo strrev("I am the cookie monster!");
//Newline
echo "\n";

//Lets try a palindrome(phrase that's the
//same forwards and backwards)

echo strrev("a man a plan a canal panama");
?>

Outputs:

!retsnom eikooc eht ma I
amanap lanac a nalp a nam a

If you put in the correct spacing on the second line it still says “a man a plan a canal panama,” but the first line is still gibberish. Below are some other useful string functions I think you should know, and their usage.

  • str_repeat(string, number of times to repeat) – Repeats a string the specified number of times
  • str_replace(string to find, string to replace it, string) – Replaces a word or words in a specified string
  • str_shuffle(string) – Shuffles are the characters in a string
  • strtolower(string) -  Turns the string to all lowercase
  • strtoupper(string) – Turns the string to all uppercase

Practice makes perfect. Play with all those function for a few minutes, and have fun.

Silly Strings

Posted on 24. Feb, 2010 by admin in Basics

We only scratched the surface of what we can do with strings.  So far we have only added text to them, and printed them out with echo. Before we move on we must examine this concept more closely to be successful in PHP. The first item we need to go over is the concatenation operator. This is just a technical term for combining strings that will come in handy later.

Let’s say you have two variables that you want to combine. The first is someone’s full name, and the second is someone’s last name. You, the developer, want to simply combine the two to retrieve the user’s full name. We do this with a concatenation operator. As you remember, before we used operators to add, subtract, multiply, etc. numbers. With a concatenation operator we are adding two or more strings together. In code this is done by adding a period in-between two string literals (the block of text inside quotes is called a  string literal) or variables. To create the full name our code would look something like this:


<?php
//Name Varibles
$firstname = "John";
$lastname = "Doe";

//Combine Them
$fullname = $firstname . $lastname;
echo "His fullname is " . $fullname;
?>

See how we can combine two string variables by putting a period in-between? As you can also see from the script we can do it with other statements, such as echo.

With the echo statement we have only been able to print text without much formatting. If you have played around with the echo function you have probably also found that some characters, such as quotes, don’t work.  A jumble of words or errors will not help us much so that is why they made escape characters.


<?php
echo "First line\nSecond line";
echo "\t\"This is tabbed over and in quotes\"";
?>

Output(Only in Plain Text):

First line
Second line     “This is tabbed over and in quotes”

A list of all the escape characters you need to know are below:

  • Newline – \n
  • Tab – \t
  • Single Quote – \’
  • Double Quote – \”
  • Dollar Sign – \$
  • Backslash – \\

You need to know all of the above escape characters. Using double quotes, a dollar sign, or any of the other characters in a regular string might cause your code to break or work incorrectly. You must use escape characters to  print the above characters.

Strings are an important concept, so let’s try a little trail an error. Try to print out some of the statements below:

Q: Combine and print $string1 = “Hello ” and $string2 = “World”

Show Answer ▼

Q: Print out “The apple is $1.25″

Show Answer ▼

Q: Print out “This is a “test” of quotes”

Show Answer ▼

Q: Print out “C:\php\index.php”

Show Answer ▼

I hope this give you a little start on how versatile strings can be, and what we can do with them. Hold on because we are not done with strings yet!

Code Challenge 1

Posted on 24. Feb, 2010 by admin in Basics

So far we have learned a number of different PHP concepts, and now it is time to test how much you were paying attention. Answer the following questions, and try some of the programming projects below. Don’t cheat!

Questions

Q: Which tags are placed between our PHP code?

Show Answer ▼

Q: Which statement is used to print text to the browser window?

Show Answer ▼

Q: What character must every PHP statement end with?

  1. Quotation Mark
  2. Semicolon
  3. Colon
  4. Period

Show Answer ▼

Q: True or false? A single line comment starts with \\.

Show Answer ▼

Q: Which of the following are incorrect variable names?

  1. A: 1stnumber
  2. B: MyString
  3. C: i_like_wildphp
  4. D: me too

Show Answer ▼

Q: What values can an integer hold? What values can a string hold?

Show Answer ▼

Q: What is the shortest statement to increase a variable by one?

Show Answer ▼

Programming Projects

Project One: Write a script that prints out “WildPHP.com is Cool”

Show Solution ▼

Project Two: Write a script prints out the degrees Celsius, from a given value in Fahrenheit.

Show Solution ▼

Operating with Operators

Posted on 24. Feb, 2010 by admin in Basics

In the previous tutorial we stored a number in a variable and printed it. Let’s take this concept to another level with PHP operators. Basically, operators are just a technical way of saying adding, subtracting, multiplying, etc. PLEASE NOTE THAT I HAVE REMOVED THE HTML TAGS. YOU STILL NEED THEM!


<?php
//Adds 5+7. Variable value is 12.
$add = 5+7;
//Subtract 9-3. Variable value is 6.
$subtract = 9-3;
//Multiply 10*10. Variable value is 100.
$multiply = 10*10;
//Divide 32/2. Variable value is 18.
$divide = 32/2;
//Modulus(Also known as remainder) 10/3. Variable value is 1.
$modulus = 10%3;
?>

See how helpful comments can be in explaining code? Instead of explaining each line of code to you, I can simply add a comment to tell what it does in plain and simple English.

You can also place a variable on the right side of the equal sign to perform operations on it.


<?php
//The variable's starting value of 10
$variable = 10;
//Lets add 5 to it to make it 15
$variable = $variable + 5;
//Subtract 9 to make it 6
$variable = $variable -9;
//Print out the final answer, 6
echo $variable;
?>

Pretty simple, huh? Well, we can make this even simpler. You can combine the operator with the equal sign to get what is called an assignment operator. You use it when you want to modify the existing variables value, just like before. You achieve the same result as the code above, but with fewer keystrokes. You can also use increment (++) and decrement(–) to move the value up or down by one, respectively.


<?php
//The variable's starting value of 10
$variable = 10;
//Lets add 5 to it to make it 15
$variable += 5;
//Subtract 9 to make it 6
$variable -= 9;
//Multiply by 10 to make it 60
$variable *= 10;
//Divide by 5 to make it 12
$variable /= 5;
//Find the remainder of 12/8 to make it 4
$variable /= 5;

//Increment to make 5
$variable++;
//Decrement to make 4
$variable--;

//Print out the final answer, 4
echo $variable;
?>

It’s a bunch to take in, so I suggest you play around with it for a few minutes before you move onto the next tutorial.

Varying Variables

Posted on 23. Feb, 2010 by admin in Basics

Simply typing in text messages with echo is not going to assist us in utilizing PHP to its fullest potential, we can just as easily do that in HTML.  The real power comes from something called variables. Just as you probably used the variable X for math equations or to store numbers, programming variables can store much more including text and sets of data. There are two types of variables that you need to know about right now, though there are many more:

  • Integers – Stores numbers like 1, 39, 519.
  • Strings – Stores text like “Hello World”, “I love PHP,” “WildPHP is cool.”

Unlike some of the other scripting languages, PHP automatically converts variable types for us. Take a look at the code below and then we will break it down.


<html>
<body>

<?php
//An integer that stores numbers
$integer = 1;
//An string that stores text
$string = "Hello World";
?>

</body>
</html>

Variables work when you place the dollar sign ($) and then put the variable name after it (for example: $variablename). Now there are some rules that you must follow:

  • Must start with a letter or an underscore ( _ )
  • Can only use alpha-numeric characters(a-z, 0-9) and underscores ( _ )
  • A variable name can not contain a space. Use underscores ( _ ) instead.

We set the value of the variable by adding an equal sign (=) and putting the value we want to set it to on the right. Like the echo statement, we must end this with a semicolon (;). To make sure this works correctly lets print our variables by putting them after the echo statement. Echo will print out the value of the variable or statement that comes after it to the screen.


<html>
<body>

<?php
//An integer that stores numbers
$integer = 1;
//An string that stores text
$string = "Hello World ";
//Print out the $string variable
echo $string;
//Print out the $integer variable
echo $integer;
?>

</body>
</html>

Output:

Hello World 1

If you are getting any errors, make sure that you have that semicolon, and your variable name does not violate any naming rules.

Note: If you are confused why it prints out “Hello World 1″ instead of “1 Hello World,” it is because $string, which contains “Hello World ” is printed first with echo. It does not mater the order of our variables above, just the order they are printed with echo.

Comments on Code

Posted on 23. Feb, 2010 by admin in Basics

So, PHP code is written for computers to understand what we want them to do, so what about us? That is where comments come in. Comments are basically just a line or two that explains what’s going on in a portion of your code. It can also be used to void a portion of your code that you do not want to run. There are two types of comments: one for single line short comments, and another for longer comments that span multiple lines.

The short single-line comments are made by adding // in front of the comment.  Multi-line comments begin with /* and end with */. Below are examples of both:


// This is a comment

/* This is a
comment that spans
multiple lines */

Comments are a pretty simple concept, but it takes practice to get them right. They are unnecessary for every line of code, but may be used every once in a while to explain what that section of the code does. Take a look at the next example and try it out on your website:


<html>
<body>

<?php
//This prints “Hello World” to the screen.
echo "Hello World";

/* This is another type of comment
that can span
multiple lines.*/
?>

</body>
</html>

See how the single line comment explains what the line below it does? We will cover proper commenting in other tutorials later.

Note: Anything that is “commented out” will be ignored by your server and not run. For example, if you put // before the echo statement in the above code, nothing will be displayed on the screen.

See how the single line comment explains what the line below it does? We will cover proper commenting in other tutorials later.

Note: Anything that is “commented out” will be ignored by your server at not run. For example, if you put // before the echo statement in the above code, nothing will be displayed on the screen.

2nd Note: You don’t need to put a semicolon(;) at the end of the comment.

Hello World with Echo

Posted on 23. Feb, 2010 by admin in Basics

Create a file called index.php and save it to the main folder of your PHP hosting. This file will always display when you go to that folder in your browser. We will be editing the code in this file during the basic tutorials as we won’t really need more than one or two files.

For the PHP code to run you have to put it in between what is called a PHP scripting block. Basically, a PHP scripting block starts with <?php and ends with a ?>.

<?php
//Your code goes here.
?>

So that it can be properly viewed in a web browser, we must enclose our PHP code in some basic HTML tags. Your code should look something like this:


<html>
<body>

<?php
\* Your code goes here. *\
?>

</body>
</html>

Now that we have a base file to work from let’s write some PHP code. The first statement we will learn is the echo statement. With this statement you can print text to the screen by putting the text in between quotes. Something like this:

<html>
<body>

<?php
echo "Hello World";
?>

</body>
</html>

This statement will print “Hello World” on the screen. Please note that after each PHP statement you need a semicolon(;). Well, there you have it! You have run your first PHP script. You can replace the text inside the quotes for PHP to present any statement you want.

Page 2 of 3123