Monday, December 23, 2013

Learn PHP from Scratch – Part 2

Picking up where part 1 of this series left off, this tutorial will continue to guide you through getting started with PHP arrays and loops. Basic fundamentals will be taught alongside their equal partners used in popular software such as WordPress.

Overview

Beginners: In order to fully understand these concepts, it is highly recommend that you first read Part 1.Part two of this series will walk through using core PHP principles that assist in everyday coding. This includes creating and using arrays and loops to store and retrieve data when you please.

Array of Light

An array is what you turn to when you find yourself creating similar variables over and over. Two words are used when referring to the contents of an array. Those words are “key” and “value”. Every array has at least 1 key and value. They will always come in pairs as the key refers to the value. There are three types of arrays: Associative, Numeric, and Multidimensional. Multidimensional arrays are simply arrays within arrays. Let’s take a brief look at the first two.

Associative Arrays

An associative array is helpful in that the key is declared by the programmer somewhere thus giving context to the value. For example I will create an array containing personal information about myself. Below you will see two ways of laying out the array in PHP. The purpose of the second is only for organization and ease of reading. As Jeffrey mentioned in part one of this series, PHP is not white-space sensitive.
  1. <?php  
  2. $personalInfo = array("name"=>"Erik Reagan","occupation"=>"Web Developer","location"=>"Savannah, GA USA");  
  3. ?>  
  1. <?php  
  2. $personalInfo = array(  
  3.     'name'          => 'Erik Reagan',  
  4.     'occupation'    => 'Web Developer',  
  5.     'age'           => 23,  
  6.     'location'      => 'Savannah, GA USA'  
  7.     );  
  8. ?>  
That’s great and all – but how do I get my information to display in HTML? I’m glad you asked! It’s very similar to displaying a variable but you add one little extra piece of data: the key.
  1. <p>My name is <?=$personalInfo['name']?> and I am a <?=$personalInfo['occupation']?> in <?=$personalInfo['location']?> and am <?=$personalInfo['age']?> years old.</p>  
Wait a second? What’s this <?=…?> mess all of a sudden? Well using <?=?> is shorthand PHP for <?php echo … ?>. In part one you learned that the echo command is similar to print in other languages. The shorthand PHP is just one way to write less code while working.

Numeric Arrays

Sometimes you don’t need to have a word associated with a value within an array. In that case you will use a numeric array which is actually created by default in PHP. Above we used the equal sign followed by the greater than sign (=>) to set array values to keys. With numeric arrays you can simply set the values and the key is assumed incrementally. Let’s take a look:
  1. <?php  
  2. $personalInfo = array(  
  3.     'name'          => 'Erik Reagan',  
  4.     'occupation'    => 'Web Developer',  
  5.     'age'           => 23,  
  6.     'location'      => 'Savannah, GA USA'  
  7.     );  
  8. $fruit = array('apple','orange','grapes');  
  9. ?>  
As you can see we have done nothing but put values in this array. PHP took care of the keys for us. As far as you beginners are concerned keys ALWAYS start at the number 0 and increase by 1 with each new array element. As you go deeper into learning about arrays you will learn that you can manipulate them at will – but that is not covered here today. “How do I know what key to use”, you may ask. The easy way in our example is just to start at zero and find your element. For example the key for “apple” is 0, the key for “orange” is 1 and the key for “grapes” is 2. Pretty simple, huh. Well sometimes your arrays will get huge and go up into the 10s and possibly hundreds. No one wants to sit there and count that mess. Your first instinct may be to simply run “echo $fruit” but it will only spit out the word “Array”. PHP gives us a few simple ways to review our array data. Let’s look at two of them.
  1. <?php  
  2. $personalInfo = array(  
  3.     'name'          => 'Erik Reagan',  
  4.     'occupation'    => 'Web Developer',  
  5.     'age'           => 23,  
  6.     'location'      => 'Savannah, GA USA'  
  7.     );  
  8. $fruit = array('apple','orange','grapes');  
  9.   
  10. print_r($personalInfo);  
  11.   
  12. var_dump($fruit);  
  13. ?>  
Note that running these in your browser may produce something quite nasty looking. The first array will especially be unattractive and perhaps difficult to read. It may benefit you to throw <pre></pre> tags around those two commands so that the white space is pre-formatted correctly. Assuming you have placed these tags around the command you should have the following printed back to you:
  1. Array  
  2. (  
  3.     [0] => apple  
  4.     [1] => orange  
  5.     [2] => grapes  
  6. )  
  7. array(4) {  
  8.   ["name"]=>  
  9.   string(11) "Erik Reagan"  
  10.   ["occupation"]=>  
  11.   string(13) "Web Developer"  
  12.   ["age"]=>  
  13.   int(23)  
  14.   ["location"]=>  
  15.   string(16) "Savannah, GA USA"  
  16. }  
The first function, print_r(), will simply print the structure and contents of your array. The keys will be on the left in brackets and the values will be to the right of the corresponding keys. In the second function,var_dump(), you learn and bit more about your data. Notice the “age” key in the $personalInfo array. The value is not in quotes like the other values are. I did this so that you could distinguish between two types of data in PHP. Anything in quotes is considered a string and in the case of the “age” data it is an integer. I won’t go into details of the other types of data but I point this out because the var_dump() function gives you some useful information.
Notice the first bit which comes in the first line “array(4)“. The first bit dumped saying “This is an array and it contains 4 sets of data”. Going down to the next line you get your key you see the first key and then it says “string(11)“. This is saying “This is a string and it is 11 characters in length” (keep in mind that a blank space is considered a character). Jump down to the “age” key and notice it says int(23). This is saying “This is an integer with a value of 23″.
Now that you know how to use print_r() and var_dump() we will move on to looping through this data.

Multidimensional Arrays

As mentioned above a multidimensional array is simply an array that contains at least one additional array as a value. I will run with the “personalInfo” example and create an array for a staff team.
  1. <?  
  2. $company = array(  
  3.     'info'          => array(  
  4.        'name'          => 'Awesome Web Company',  
  5.        'location'      => 'Savannah, GA',  
  6.        'website'       => 'http://weAreAwesome.com'),  
  7.     'staff'         => array(  
  8.         array('name'=>'Kermit the Frog','position' => 'CEO'),  
  9.         array('name'=>'Hiro Nakamura','position' => 'Art Director'),  
  10.         array('name'=>'Willy Wonka','position' => 'Web Developer')  
  11.      )               
  12. );  
  13. ?>  
As you can see multidimensional arrays can get intricate. This is an odd example because typically this type of data would be stored in a database and pulled in with PHP later. However, for the sake of learning about arrays we will start with the data within PHP. The first key in this array is called ‘info’ and it’s value is actually an associative array containing company information. The second key of our $company array is ‘staff’ and it’s value is a numeric array. Let’s take a look at the structure before we begin. Running print_r($company)will produce the following:
  1. Array  
  2. (  
  3.     [info] => Array  
  4.         (  
  5.             [name] => Awesome Web Company  
  6.             [location] => Savannah, GA  
  7.             [website] => http://weAreAwesome.com  
  8.         )  
  9.   
  10.     [staff] => Array  
  11.         (  
  12.             [0] => Array  
  13.                 (  
  14.                     [name] => Kermit the Frog  
  15.                     [position] => CEO  
  16.                 )  
  17.   
  18.             [1] => Array  
  19.                 (  
  20.                     [name] => Hiro Nakamura  
  21.                     [position] => Art Director  
  22.                 )  
  23.   
  24.             [2] => Array  
  25.                 (  
  26.                     [name] => Willy Wonka  
  27.                     [position] => Web Developer  
  28.                 )  
  29.   
  30.         )  
  31.   
  32. )  
Now our company information is ready to be accessed. We access the internal arrays the same way we accessed our personal information earlier. Here’s an example of using data from this multidimensional array:
  1. <h1><?=$company['info']['name']?></h1>  
  2.   
  3. <p>Located in <?=$company['info']['location']?> and online at <a href="<?=$company['info']['website']?>"><?=$company['info']['website']?></a>.</p>  
  4.   
  5. <h2>Our CEO</h2>  
  6. <p><?=$company['staff'][0]['name']?></p>  
Now that we have a grasp on arrays lets jump into loops which will minimize the time we spend parsing the array data.

Loops

Loops will come in quite handy as the amount of data you work with increases. We’ve gone into arrays so that naturally leads us to loops. In the last code snippet we listed a staff member within the $company array. What if we want to cycle, or loop, through each staff member and display the information in a uniform fashion? Well in comes the foreach loop. Just like the function sounds it will do a specific action for each of the elements within an array or object. It typically looks like this:
  1. <?php  
  2. foreach($array as $key => $value) {  
  3.     ...some code here  
  4. }  
  5. ?>  
Notice the three variables passed to this function. The first is simply the array we are working with. The second and third variables are defined by YOU and can say anything you want. These are what refer to the array’s data inside the curly brackets. We will look at this in a moment. But first, just like the echo command has a shorthand or alternate syntax, foreach has something that will help transverse between PHP and HTML. This way it keeps the code as clean as possible. It looks like this:
  1. <? foreach($array as $key => $value) : ?>  
  2. <p>Some html and some php will go here</p>  
  3.   
  4. <? endforeach; ?>  
You will see this format in if statements and while loops as well (in WordPress for example). Now that we’ve looked at the format of this function let’s put it in action. Going back to the company information array let’s build a nice page with that data
  1. <?  
  2. $company = array(  
  3.     'info'          => array(  
  4.        'name'          => 'Awesome Web Company',  
  5.        'location'      => 'Savannah, GA',  
  6.        'website'       => 'http://weAreAwesome.com'),  
  7.     'staff'         => array(  
  8.         array('name'=>'Kermit the Frog','position' => 'CEO'),  
  9.         array('name'=>'Hiro Nakamura','position' => 'Art Director'),  
  10.         array('name'=>'Willy Wonka','position' => 'Web Developer')  
  11.      )               
  12. );  
  13. ?>  
  14.   
  15.       
  16. <h1><?=$company['info']['name']?></h1>  
  17. <p>Located in <?=$company['info']['location']?> and online at <a href="<?=$company['info']['website']?>"><?=$company['info']['website']?></a>.</p>  
  18.   
  19. <h2>Our Staff</h2>  
  20.   
  21. <ul>  
  22. <?php foreach ($company['staff'as $person) : ?>  
  23.   <li><?=$person['name']?> is our <?=$person['position']?></li>  
  24.   
  25. <?php endforeach; ?>  
  26. </ul>  
In this instance the foreach loop cycles through each staff member and displays the HTML and PHP we told it do. I knows exactly how many staff members are in the array so it stops once it gets to the end. I’m sure you can see how useful this can become.

Additional Resources

Although this tutorial may seem to ‘unleash the power of arrays and loops’ it really just scratches the surface. I highly encourage anyone interested (and that means YOU if you’re still reading this) to read through the PHP online docs for the version you are using. You can find them at php.net. We only used one type of loop in this tutorial, the foreach loop. There are others like fordo…while and while that you will also gain use from knowing about.