PHP Tutorial #1: PHP Basics (Beginner)
Categories: PHP Tutorials
Ok, so this begins my series of PHP Tutorials. I’m planning on doing some for other languages. These tutorials will not usually be in any particular order, and usually, unless otherwise specified, they will not be directly related, though some may use things discussed in previous tutorials. Each tutorial will be ranked either beginner, intermediate, or advanced. So, here goes!
In this tutorial, we’ll be going over the very basics of using PHP in a web page.
Introduction
PHP Is a very easy language to learn, especially if you’re familiar with a C-like language. However, it can still prove quite difficult to master. Don’t expect to memorize everything you’ll ever have to do in it. I’ve been working in PHP for 5 years now, and I still have to look functions up. This tutorial assumes you already have a suitable development environment. There are plenty of tutorials of how to set up Apache/PHP on a wide variety of operating systems, and that is beyond the scope of this article. Alright, let’s get our hands dirty.
Basics
If you’re reading this article, you’re probably familiar with HTML. If so, you know what .html files, and their outdated, older brothers, .htm files are. Pages with PHP code in them do not use this file type. They are suffixed with .php, which just lets our web server know that they need a little bit of pre-processing before they’re ready to display. These files, usually, are just HTML with PHP code injected. This is accomplished by using <?php ?> or <? ?> for shorthand. While it is perfectly acceptable to use either aforementioned syntax, I generally recommend that you stick with <?php ?> because if you use XHTML, you MAY have issues with collision with <?xml ?> stuff.
Here is an example of how to output “Hello, World!” on a page in bold using PHP:
<html>
<head>
<title>Hello, World Example - PHP<title>
</head>
<body>
<strong><?php print "Hello, World!"; ?></strong>
</body>
</html>You can probably deduce exactly what is happening from the code above, but just in case, let’s break it down.
<?php- This is lets PHP know it’s time to do work on 22s.print- This is a construct within PHP. In essence,printis a function, however there are certain rules it does not have to follow that functions do. For example, we can call it without parenthesis, whereas if I wanted to call a function, I would have to saymyFunc( )."Hello, World!"- This is the string we’re telling PHP to print out. This could be anything though: an integer, a floating-point decimal, or an array. PHP is a very loosely-typed language, meaning that you don’t have to declare the type of a variable when you declare the variable.?>- This closes the PHP block.
Here are some other basic examples of how to do things in PHP:
<?php // This is a comment. It's skipped by the processor, and is only seen when viewing your code, not on the presentation side. # You can also use a pound sign at the beginning of a line to make comments. /* This is a different kind of comment... ...it spans multiple lines. */ $myVar = 0; // here we're creating a variable and setting its value to zero // Here are some basic mathematical operations in PHP $myVar = 1 + 1; // addition $myVar = 1 - 1; // subtraction $myVar = 1 * 1; // multiplication $myVar = 1 / 1; // division // Here are some more advanced operations $myVar = 3 % 2; // modulus. this will divide 3 / 2, and store the remainder in $myVar $myVar ++; // this will increment the value by 1 $myVar --; // this will decrement the value by 1 $myVar += 3; // this will add 3 to the current value of $myVar $myVar -= 5; // this will subtract 5 from the current value of $myVar print $myVar == false; // this will print 'true', as 0 evaluates to false in PHP print $myVer == null; // this will also print 'true', as 0 also evaluates to null in PHP /* This is one way of doing an if..else statement. Notice, the exclamation point in the statement being evaluated in the if. That's the equivalent of saying '$myVar == false'. */ if ( !$myVar ) { print '$myVar is false!'; } else { print '$myVar is NOT false!'; } // There's also "else if". For example: if ( !$myVar ) { print '$myVar is null!'; } else if ( $myVar == 1 ) { print '$myVar is 1'; } else { print '$myVar is not null or 1'; } // here is another way of doing an if..else. Notice the colons and the 'endif'. if ( !$myVar ) : print '$myVar is false!'; else : print '$myVar is NOT false!'; endif // if you only have one line to be executed per condition, then you can do this if ( !$myVar ) print '$myVar is false!'; else print '$myVar is NOT false!'; // You can also mix and match between the first and last I showed you. For example: if ( !$myVar ) print '$myVar is false!'; else { // on the next line we're using the concatenating operator ('.') to outprint the value of $myVar print '$myVar is ' . $myVar . '. Setting $myVar to null'; $myVar = null; } // Finally, there are what are called "ternary" statements. It's the last type of true if..else !$myVar ? print '$myVar is null!' : print "\$myVar is $myVar"; /* Here's how this breaks down: !$myVar ? print '$myVar is null!' : print "\$myVar is $myVar"; |--1--|-2-|----------3-----------|-4-|-----------5-------------| 1: this is the conditional statement (what you would put in the "if" of the if..else) 2: this operator begins the block of code to execute if the statement is true (the "if") 3: this is the block of code to execute if the statement is true 4: this operator begins the block of code to execute if the statement is false (the "else") 5: this is the block of code to execute if the statement is false */ // The final type of conditional structure is a switch. switch ( $myVar ) { case 0: print '$myVar is null!'; break; // note: this automatically jumps out of the control structure case 1: print '$myVar is 1!'; break; // we break because we've already found the case we want default: // this is the 'else' of this structure print '$myVar is not null or 1!'; // we don't have to break here, because we're already at the end of the structure } /* In some cases you may not want to break. You may want to match the proper case and then perform the actions for ever case after that. */ /* had we used double-quotes above, the concatenating operator would not have been needed, though it's usually easier to read. For example: /* print "\$myVar is $myVar"; // notice we had to escape ('\') the first $ so it shows '$myVar is 0' /* The last thing I'm going to cover in this article is arrays. There are two ways to use arrays: - non-associative - associative */ // Non-associative Array $myArr = array( "blue", "red", "green", "yellow" ); // this creates a new array /* One of the most important array functions you'll use is 'count'. You simply pass it an array and it tells you how many values there are in the array. It's worth noting that count will always return a number greater by one than the highest index in the array, as the array starts on 0. We use this to our advantage ;-) */ // One way to add things to the array is this: $myArr[count($myArr)] = "orange"; // We've added "orange" as the 5th element (index of 4) // Another way array_push( $myArr, "purple" ); // this adds "purple" as the 6th element (index of 5) /* Now we move on to associative arrays. As you may guess by the name, there is an association made that is not made with non-associative arrays. Here's how we define an associative array: */ $myArr = array ( 'red' => 'Red', 'green' => 'Green', 'blue' => 'Blue', 'yellow' => 'Yellow' ); /* In this example, we're giving each index a key to access each value by. The original way using numbered indexes still works as well; */ print $myArr['red']; // this will output 'Red' print $myArr[2]; // this will output 'Blue' $myArr['orange'] = 'Orange'; // this adds 'Orange' with a key of 'orange' to $myArr // You can also remove values from an array. There are two main ways to do this: array_pop( $myArr ); // this way removes the value at index 0, shifts all indexes down one, and // returns the value removed. unset( $myArr[2] ); // this way just removes the value passed to it and shifts the indexes above // it down one. It's worth noting that you can unset almost any variable, not // just array indexes ?>
Conclusion
Alright, so that’s it for this tutorial. If you have any questions, comments, concerns, or criticism, please feel free to leave me a comment.
Tags
You can leave a comment, or send a trackback from your own site.
Awesome 1st tutorial. To cover all the bases, you might consider adding tertiary and switch explanations, as well as what an array looks like. When I first started PHP, those always confused me.
Beginning/intermediate cats like me would be interested in seeing something outside the php manual, like using var_dump and other cool tricks to diagnose bad code or locate important variables.
Thanks for the suggestions. I just added ternaries and switches, as well as arrays and even some basic and a little more intermediate mathematical operations.
If you have any other suggestions for something I should cover in my next one, I’m all ears.