Learn PHP From Scratch

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.

<?php
$personalInfo = array("name"=>"Erik Reagan","occupation"=>"Web Developer","location"=>"Savannah, GA USA");
?>
<?php
$personalInfo = array(
	'name'          => 'Erik Reagan',
	'occupation'    => 'Web Developer',
	'age'           => 23,
	'location'      => 'Savannah, GA USA'
	);
?>

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.

<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:

<?php
$personalInfo = array(
	'name'          => 'Erik Reagan',
	'occupation'    => 'Web Developer',
	'age'           => 23,
	'location'      => 'Savannah, GA USA'
	);
$fruit = array('apple','orange','grapes');
?>

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.

<?php
$personalInfo = array(
	'name'          => 'Erik Reagan',
	'occupation'    => 'Web Developer',
	'age'           => 23,
	'location'      => 'Savannah, GA USA'
	);
$fruit = array('apple','orange','grapes');

print_r($personalInfo);

var_dump($fruit);
?>

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:

Array
(
    [0] => apple
    [1] => orange
    [2] => grapes
)
array(4) {
  ["name"]=>
  string(11) "Erik Reagan"
  ["occupation"]=>
  string(13) "Web Developer"
  ["age"]=>
  int(23)
  ["location"]=>
  string(16) "Savannah, GA USA"
}

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.

<?
$company = array(
	'info'          => array(
	   'name'          => 'Awesome Web Company',
	   'location'      => 'Savannah, GA',
	   'website'       => 'http://weAreAwesome.com'),
	'staff'         => array(
	    array('name'=>'Kermit the Frog','position' => 'CEO'),
	    array('name'=>'Hiro Nakamura','position' => 'Art Director'),
	    array('name'=>'Willy Wonka','position' => 'Web Developer')
	 )
);
?>

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:

Array
(
    [info] => Array
        (
            [name] => Awesome Web Company
            [location] => Savannah, GA
            [website] => http://weAreAwesome.com
        )

    [staff] => Array
        (
            [0] => Array
                (
                    [name] => Kermit the Frog
                    [position] => CEO
                )

            [1] => Array
                (
                    [name] => Hiro Nakamura
                    [position] => Art Director
                )

            [2] => Array
                (
                    [name] => Willy Wonka
                    [position] => Web Developer
                )

        )

)

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:

<h1><?=$company['info']['name']?></h1>

<p>Located in <?=$company['info']['location']?> and online at <a href="<?=$company['info']['website']?>"><?=$company['info']['website']?></a>.</p>

<h2>Our CEO</h2>
<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:

<?php
foreach($array as $key => $value) {
	...some code here
}
?>

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:

<? foreach($array as $key => $value) : ?>
<p>Some html and some php will go here</p>

<? 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

<?
$company = array(
	'info'          => array(
	   'name'          => 'Awesome Web Company',
	   'location'      => 'Savannah, GA',
	   'website'       => 'http://weAreAwesome.com'),
	'staff'         => array(
	    array('name'=>'Kermit the Frog','position' => 'CEO'),
	    array('name'=>'Hiro Nakamura','position' => 'Art Director'),
	    array('name'=>'Willy Wonka','position' => 'Web Developer')
	 )
);
?>

<h1><?=$company['info']['name']?></h1>
<p>Located in <?=$company['info']['location']?> and online at <a href="<?=$company['info']['website']?>"><?=$company['info']['website']?></a>.</p>

<h2>Our Staff</h2>

<ul>
<?php foreach ($company['staff'] as $person) : ?>
  <li><?=$person['name']?> is our <?=$person['position']?></li>

<?php endforeach; ?>
</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 for, do…while and while that you will also gain use from knowing about.

Add Comment

Discussion 89 Comments

Comment Page 2 of 2 1 2
  1. honour chick says:

    thanks alot… i still have a long way to go though. hope you continue with the tutorials :)

  2. Alex says:

    great stuff, as previously stated <? shorthand tags are to be avoided as they dont work with php 5, i used to get it working

  3. igmuska says:

    Awesome tutorial, short and to the point…looking forward to more

  4. Steve says:

    When coding, what’s best practice? What “rule of thumb” do you guys use for using an apostrophe versus quotes?

  5. mike says:

    Quickly approaching the 3 month mark since part 2 was published, is there a part 3 on the horizon?

  6. I hope part 3 is coming as well. This was an excellent example for arrays. One thing i noticed amongst alot of i different php frameworks is there strong use of arrays. I think this is one of the most important concepts that one should know with php.

    Thanks again for a great tutorial.

  7. mike says:

    I agree, I have been told by many developers that arrays are something you should have a very solid understanding of.

  8. Vinay Vidyasagar says:

    good stuff but the coding with short forms worries me coz it confuses the first time readers and its generally not a good practice. atleast thats what my mentors have taught me :0 cheers. waiting for part 3 :D

  9. Great tutorial! Short and to the point

  10. Paul says:

    Thanks for the tutorial… I would love if you could put out part 3 and beyond.

    • Pablo says:

      Hi Bob! Glad to hear from you again. Yup, we’re in Athens for six weeks while my wife does a cnotervasion internship in the labs at the Agora dig, primarily conserving ethnographic objects (pottery, etc).Sounds like you’ve got a pretty sweet gig going as well! I’m actually about to begin a masters’ degree program in the History of Design, so I’m sure I could learn a lot from you!Cranking away on modo stuff today, actually! More soon :)Adam

  11. Jeffrey Way says:
    Staff

    @Paul – Take a look at the “Diving into PHP” video series at blog.themeforest.net.

  12. codex73 says:

    Where is part one?

  13. Andres Felipe says:

    this tutorials are so freaking awesome!! I’m just a student of interactive design whos learning PHP, and actually I don’t really need it right now but I know I will use it some day.

    I have tried to find a great tutorial that treaches me PHP but it’s been an unsuccessful quest. So thank for this kinda tutorial made for kids like me lol!!!!! if you have any page that helps us with PHP please post it

    thank you again, tuts+ have saved my life countless times.

  14. medyum says:

    Nice addition to the series… definitely for newbies, but I probably fall under that umbrella somewhere so I’m just happy to see more easy to follow tutorials out there like this. Looking forward to seeing the next pieces of this series! Thanks for the post

  15. medyum says:

    Nice tutorial. Like said before you use shorthand PHP tags in some places and full tags in other places.

  16. büyüler says:

    it is very god blog ,thanks

  17. medyum says:

    this is very nice blog,thank you for all

  18. ankara parke says:

    Thanks for the tutorial… I would love if you could put out part 3 and beyond.

  19. Art says:

    what happened to part 1?

  20. Nice addition to the series… definitely for newbies, but I probably fall under that umbrella somewhere so I’m just happy to see more easy to follow tutorials out there like this. Looking forward to seeing the next pieces of this series! Thanks for the post

  21. smackdown says:

    Thanks a lot for the wonderful information

  22. Medyumlar says:

    it is very god blog ,thanks

  23. Good information and good way your blog post. Good luck blogger man.

  24. Thanks for admin wonderful web site..great information

  25. evlilik says:

    Thanks good work men

  26. dilsayar says:

    Thank for the starters. They are really helpful. the links in the first article are good places to start. I guess
    I will start a starters PHP kit in Turkish;)
    http://dilsayar.com/blog/?p=65

    Thanks again

  27. medyum says:

    Very nice sharing.thanks

  28. gen says:

    Where is part 3 bring this nack from the dead

  29. nakliyat says:

    very nice web portal

  30. medyum says:

    good web sites portal

  31. Thanks for the tutorial… I would love if you could put out part 3 and beyond.

  32. Very good information on this subject and excellent quality of the Website. Regards from Santiago de Chile

  33. Colby says:

    I guess this is where the series stops? Part 2.

Comment Page 2 of 2 1 2

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.