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.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.clipcroma.com jonatan

    great for newbies

  • http://www.jasonstanbery.com Jason

    Great article for learning php but there are couple things that people may find confusing.

    You have print_r assigned to the personalInfo array and var_dump assigned to the fruit array then the results show that the var_dump was used on personalInfo and the print_r was used on the fruit.

    In the section on multidimensional arrays you use shorthand instead of which I always read was bad. Things may have changed, I could be smoking crack, or I’ve been tricked into typing 3 unneeded letters all this time.

  • Chris

    Great, thanks so much for this! So simple to follow, you guys make it look easy.

    I’ve never actually seen “endforeach;” in use, rather opening and closing brackets…

    $value) { ?>
    Some html and some php will go here

    Can’t wait for the next one, hope it’s real soon!

  • http://jeremysimkins.com/ SoN9ne

    Short hand is not bad, its just recommended to not use it because most servers are not setup to use it. It is a good rule to always use <?php instead of <? when programming because then all servers can use your code no matter what the short tag setting is. Personally i never use the short tags. I write a few open source projects as well as develop a corporate social networking blogging platform that specializes in SEO. I would say this is a very nice tutorial, it is easy to read and understand. Nice job on this.

  • Momo

    Be careful at this

    <?= wrong for php5 version

    use this :

    <?php echo ‘…………………..’;

    A bientôt

  • http://www.evanbot.com Evan

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

  • http://www.contempographicdesign.com Chris Robinson

    Great tutorial

  • http://www.insicdesigns.info insic

    at last its here. its quite a long wait. hehehe thank you very much.

  • http://www.insicdesigns.info insic2.0

    why my other username are block in nettuts. y i cant comment?

  • http://www.insicdesigns.info sinned

    wow i am muted. why?

  • http://www.makedesignnotwar.com Make Design, Not War

    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

  • http://erikreagan.com Erik Reagan
    Author

    @Jason
    I noticed the print_r and var_dump swap (along with a couple of other minor issues) this morning and just didn’t get my corrections to the editor in time. I promise to be a better proof reader next time :)

  • http://joshmmiller.com Josh

    Thanks for this. I am really excited about this series :D

  • http://www.1pixelbrush.com Dan

    yeah, continued

  • Gonzalo

    @Momo, I think it’s enabled by default, maybe your hosting has disabled it. You can enable it from php.ini or with a .htaccess file. Check the PHP documentation: http://www.php.net/manual/en/ini.core.php

  • http://paulgendek.com Paul Gendek

    I use short tags when it’s just a basic LAMP server, and the echo shorthand is best used in direct HTML code – easiest to type, and easiest to read later

  • http://www.solutiondesigns.net Philo

    Nice Article! :)

  • http://www.freshclickmedia.com Shane

    interesting post. Also interesting in reading some of these comments too.

    @insic, @sinned – not quite sure what you’re both getting at. It seems you’re mentioning that you cannot comment, yet your comments are shown.

    Hmmm…

  • http://www.freshclickmedia.com Shane

    Oh yeah – see what you mean – comment doesn’t appear immediately. :)

    Is that why you keep submitting 2 consecutive comments insic?

  • http://erikreagan.com Erik Reagan
    Author

    Thanks for the kind remarks thus far.

    I just realized my “Loops” header was edited. It was a mixture of a nerd & shakespeare joke. Originally it read “Wherefore Art thou Loops”

  • Miles Johnson

    Decent basic article but DO NOT USE THE FOLLOWING:

    The opening tag must be <?php not <?. The later is outdated and will not work on some windows servers and environments.

    Stop using <?= also to echo your data, that is old and incorrect stated above. In PHP 5.3 that is soon to come out, those tags will no longer be valid and will be removed/cause errors.

    Learn to stay away from those, <?php and echo are your friends.

  • http://www.ben-griffiths.com Ben Griffiths

    Nice article, good little series so far :)

  • http://www.simpleeffect.com Snorri3D

    NICE! Keep this up this is good stuff for newbies in php as me :D

    THANKS!

  • Erik

    Nice one, but like others already said: do _NOT_ use the shorthand “<?=”, as tempting as it may seem. They are depricated as of PHP6, and a lot of servers running PHP5 don’t support them either (by default). Set up your editor to insert a snippit (like: ), to make it easier on yourself.

  • http://erikreagan.com Erik Reagan
    Author

    A number of you have brought up an excellent point that I failed to acknowledge. While PHP has many settings that are customizable I was assuming certain setting for certain lines of code. The last place one should write setting-specific code is in a “intro to” tutorial. Also – I was unaware that PHP 6 will be deprecating the shorthand <?=…?>.

    On a similar note I have no idea how the <? … ?> go in there. I never code with that but somehow I did that in the tutorial. My apologies there.

    My primary reason for working with the shorthand <?php foreach(…) : ?> … <?php endforeach; ?> was to familiarize that code with those who may look at WordPress code down the road.

  • http://www.insicdesigns.info sinned

    @shane yeah thats what i mean. and im sorry guys for posting two consecutive comment.

  • http://www.ben-griffiths.com Ben Griffiths

    Hi @Erik – is there anywhere that shows the changes including the removal of < ? =, I can find lots of changelogs for PHP6, but nothing that mentions that shortcode being removed…

  • David Smith

    Hi,

    Great article for newbees. Please can you do a article on OOP in PHP. Start really simple and build towards practical examples.

    How about article on using PHP with MYSQL?

    Thanks

  • http://andrisetiawan.net ahnShev

    That will be very useful for me. thanx :D

  • http://www.kivodesigns.com Kivoiam

    Awesome! Thanks for the building of a great Foundation.

  • http://www.1stwebdesigner.com Dainis Graveris

    Thanks for the second part about PHP!
    Appreciated! Kep up the good work!

  • http://broof.de BroOf

    very useful tutorial! Please more of this kind! Love it!

  • http://www.lostkore.es Lostkore

    Wish someone had done something as clear as this when i started learning PHP.
    Thank you for taking time to make this.

  • Preben

    Hi, I would recommend to watch Phpvideotutorials.com – there’s lots of very good free video tutorials there to watch. Anyway, this tute is also good!

  • http://webdesignerthings.com/ Benjamin David

    Nice article, thanks !

  • Pingback: pligg.com

  • http://maiconweb.com Maicon

    Well learned. Continue please.

  • http://www.davidtucker.net David Tucker

    Great tutorial man! I think this information is perfect for people that are new to PHP.

  • http://www.estudigital.com Estudigital

    Great and usefull!

  • http://www.designbykai.nl Kai C

    Thanks!! learned a lot from this tutorial :)

  • http://www.jonathansace.com John

    Arrays are very useful, thanks a lot.

  • Dennis

    Great!

  • Dennis

    I want to see part 3:>

  • Dennis

    I want to see part 3:> when ?

  • http://www.seansteezy.com sean steezy

    hey, this was awesome, but like the dude, above, I am eager to see the next part. take your time so I hope it will be as good as the previous two!

    thanks!!!

  • http://erikreagan.com Erik Reagan
    Author

    Sorry part 3 is taking so long. My life is insane right now with my daughter in the hospital (born premature). She should be home really soon and when she is I’ll complete the series while I’m off work and get this ball rolling again. Thanks for the patience everyone!

  • http://www.imhighblood.com ericb

    thanks for the follow up, erik, looking forward to this series since i’m just starting to learn PHP! congrats on your new baby! :)

  • http://URL(Optional) mike

    Our CEO

    Any idea why that code wouldn’t be working for me? I have it setup the exact same way, I am getting no errors, but it is not displaying the results from that part of the array.

  • http://URL(Optional) mike

    “”

    that’s the part that isn’t working for me

  • http://URL(Optional) mike

    $company['staff'][0]['name']

    geez…sorry. this part here.