• About
  • Forum
  • Write For Us
  • Contact
  • Top 50 Photography Blogs
  • Resources
  • Archives

IndustryDev

Web Design & Photography Blog

  • Design
    • Lightroom
    • Photoshop
    • Bridge
    • Camera Raw
  • Development
    • HTML
    • CSS
    • JavaScript
    • PHP
    • Dev Tools
    • WordPress
  • Photography
  • Blogging
    • SEO
  • Technology
    • Hosting
  • Inspiration
    • Interviews
    • Learning
You are here: Home / Archives for PHP
Have a question? Ask it and help others in our new discussion forums.

PHP Coding Tips, Tutorials & Techniques

The PHP section includes posts and articles that cover tips, tutorials and best practices for various areas of coding websites with Hypertext Preprocessor. Discussion includes how to effectively utilize PHP to build dynamic, database driven websites and applications. Additional topics include syntax and structure, datatypes, operators, conditionals, loops and functions.

PHP Code Used in WordPress

June 18, 2015

PHP Code Used in WordPress

Most of the PHP code you’ll need for your WordPress install can be found in the codex. The codex is simply a huge repository of instructions, code and support. It’s a wonderful place for WordPress developers to hang out because, not only does it contain much of what you’ll need to answers questions and solve problems, it’s also a really nice learning opportunity. The more you browse, the more you begin to understand the inner workings of how much of WordPress is assembled.

While the codex is a large area with tons of code, in this post, we’re only going to concern ourselves with theme development. So, if you scroll down towards the middle of the main codex page, you’ll see a heading called, “Working With Themes.” We’ll be in there.

Template Tags

If you’ve ever used jQuery, you may be familiar with the idea behind how WordPress template tags work. Basically, instead of forcing a website developer to write out long blocks of JavaScript code or a WordPress developer to write out long blocks of PHP code, the developers behind both jQuery and WordPress have done that already. They’ve written the code behind the scenes and condensed it into nice, pretty keywords. When we call these simple keywords in our code, we’re telling the behind the scenes code to wake up and do what’s it’s made to do.

Inside the WordPress codex, there’s an area that lists all template tags by category. If we visit the page, we can locate the category we’re interested in and browse through each template tag that category contains. If something looks helpful, we’re able to click that tag and visit the actual tag page that contains all the information related to it.

By default, template tags do something. They either return something short and simple or return something much more complex. To take advantage of the short and simple tags is easy. You simply place the tag in your PHP code inside your template file. You may end up with a URL or a title or something as straightforward as that. Taking advantage of the more complex tags requires a bit more thought. In some cases, you’ll have to tell WordPress exactly what you’re interested in accomplishing by using what are called, “parameters.”

For instance, if we look at the “the_title” template tag, we can see that it accepts three parameters – $before, $after and $echo.

<?php the_title( $before, $after, $echo ); ?> 

Each of these parameters plays a different role. For many template tags, parameters are optional. For others, they’re required. Fortunately, all optional and required parameters are listed and described on its related template tag page. In this post, I’ll go over some examples of what I’m talking about.

Conditional Statements & Loops

This is the part where you wish you had programming experience. Not that it’s immensely difficult or anything like that, but I think things would progress rather smoothly with the understanding of a few coding concepts, such as the ones you acquire when studying either PHP or JavaScript. Fortunately for us, these concepts are found in the “101” level for both of these languages, so once you become comfortable with the basic ideas behind conditional statements and loops, the rest just has to do with syntax. Before we begin though, let me give a few definitions:

Conditional Statements: In computer science, conditional statements, conditional expressions and conditional constructs are features of a programming language which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false. (source)

Loops: In computer programming, a loop is a sequence of instructions that is continually repeated until a certain condition is reached. (source)

The foundation of conditional statements (or conditionals) and loops throughout much of programming is common. And as I stated above, the concepts aren’t all too challenging to grasp. In the most basic sense, in WordPress, a conditional and loop is constructed something like this:

IF posts exist and WHILE they exist
// DISPLAY CONTENT
ELSE
// DISPLAY NO CONTENT MESSAGE

All the information on WordPress loops can be found in the codex. And lucky for us, I’ve already written a fairly in-depth post that covers some of the ins and outs of the loop.

Understanding the WordPress Loop

WP_Query

A while back, I wrote a post that covered a bit of working with WordPress templates. In that post, I talked about something called, “WP_Query.” WP_Query is the ultimate when it comes to making your WordPress loop output a certain way. It can filter which posts display on a certain page, sort them a specific way, display posts written by one or many authors and more. It really is a tool that needs to be worked through. The codex page I linked to above is a long one and gives great examples of how WP_Query can be used.

Instead of writing any code examples, I’ve decided that linking to external blog posts might be more helpful when it comes to talking about this topic. Truthfully, a conversation on WP_Query is a post unto itself and I think it’s beyond the scope of what I’m talking about here. So, if you’re interested in delving deeper into WP_Query, please take a look at the resources below:

Using WP_Query in WordPress – Smashing Magazine

Custom WordPress Loop With Pagination – Call Me Nick

An Introduction To WP_Query | Elegant Themes Blog

Mastering WP_Query: An Introduction – Tuts+ Code Tutorial

——

I know this was only the beginning of a chat regarding the use of PHP in WordPress and that’s why I intend to continue writing on this topic in future posts. For now though, if you’ve got any comments or questions, please leave them below. Also, if you would like to browse through my articles on WordPress, please take a look at my WordPress category.

Filed Under: Development Tagged With: PHP, WordPress


Working With PHP in WordPress

June 13, 2015

Working With PHP in WordPress

It’s the strangest thing – since I’ve begun delving into the world of coding, I’ve heard very little in terms of PHP. It seems that the majority of folks who are attempting to get into this field are more concerned with JavaScript, Python and the plethora of tools that emerge daily. That strikes me as odd, considering how prevalent PHP is on the web. I’ve been working online since the beginning of the century and right behind HTML and CSS, PHP has been where it’s at. To each their own, I suppose.

Treehouse has finally released their latest WordPress course by Zac Gordon, called, “PHP for WordPress.” I’ve been looking forward to this course because, while I’m taking courses in straight up PHP as well, learning PHP specifically as it relates to WordPress is going to be a huge time saver. Since WordPress will be my primary focus moving forward in life and since there are only so many hours in the day, learning advanced PHP probably isn’t in the cards. Getting a grip on what levels of PHP are used by WordPress developers will help immensely.

With that in mind, let’s get started with my notes for Zac’s new course.

PHP Files

If you’ve looked into working with PHP at all, you most likely understand that the files used with PHP, end in .php. Within these files, you can write both HTML and PHP. Some applications use only files that end in .php for every single file they use.

Inside WordPress, there are three primary areas that contain PHP files. They are:

Core Files: If you have no idea what these files are, don’t touch them. These are files that run your installation of WordPress. If you go ahead and edit any of these files and you aren’t a WordPress core developer, you’ll most likely break your install. Much like with any CMS, these types of files run behind the scenes and aren’t meant to be edited by theme developers and the such.

Theme Files: These files are the ones you’ll most likely concern yourself with when developing for WordPress. Theme files control the look and function of the front-end of your WordPress install. They contain HTML and PHP code. In this and later posts, we’ll be talking a lot about theme files in WordPress. If you’d like to see some articles where I’ve already gone into some pretty good detail on this, check out my posts on WordPress.

Plugin Files: Unless you’re a plugin developer, don’t touch these files either. These types of files contain HTML, PHP, CSS and JavaScript. You may want to mess around with these types of files if you’re trying your hand at creating a WordPress plugin or are editing something in someone else’s plugin.

Now that we’ve got that out of the way, the question is, “I want to work on those template files. Where the heck are they?” If you look at an install of WordPress, you’ll see a bunch of files and folders. You can safely ignore mostly everything you see, except for the “wp-content > themes” directory.

If you look inside the “themes” directory, and you’re running a basic install of WordPress, you’ll most likely notice a few default WordPress themes. It’s common for folks to want to modify these themes to make them more suited to their own website, but there are a few words of caution that come with modifying default themes – at times, these themes are updated by the WordPress core developers. If you edit any of these “parent” default themes and the theme is automatically updated, those updates will be written over, meaning all your hard work will be lost. It’s better, and wiser, to create a “child” theme that’s not written over during a theme update.

For example, if you have a theme called, “twentyfifteen,” you shouldn’t edit any files directly in that theme. Instead, you should create a new directory called, “twentyfifteen-child-theme” and copy the file that you’d like to edit, from the original directory, to your new directory. Once it’s there, edit away. WordPress will automatically detect a new file and use it when displaying your website.

Editing Theme PHP Files

When it comes to editing WordPress files, we have a few choices. We can either set up a local server environment on our computer and work from that, work directly from a live server or work on our WordPress files locally and upload them to a live server piece by piece. Let’s go over each option.

If you wanted to go ahead and set up a local environment, you’ve got some choices. They are:

MAMP & MAMP PRO

XAMPP

DesktopServer

WampServer

Instant WordPress

There are more solutions than this, but what I’ve listed here is a good start. Basically, you’d set up a server environment to do your editing and creating from and once everything looks and functions as you’d like, you would upload the entire project to your live server. This is, obviously, the safest way to go about working on a website because of the division between a production environment and a live environment.

The next option you have for editing WordPress PHP files is to work directly from a live server. Once you’ve got WordPress installed, you could either head to the “Appearance > Editor” area in the WordPress admin and have at it. You could, alternatively, use an FTP client to edit the PHP files directly. This would be considered the least safe option there is for editing files because of the lack of the “undo” feature. If you write some code that doesn’t work or code that is way off, you’re going to have a tough time tracking down or reversing your errors.

The last option we have to editing our project is to have a WordPress install live on a server and a backup copy stored locally. This is a mix between the two previous options because you can edit files locally, with all the safety that comes with that, and upload them to a live environment when the files are ready.

Writing Actual PHP

Whichever choice you make, there’s going to come a time when you need to write actual PHP code. I already discussed that PHP files are regular text files that use the .php extension, but I haven’t talked about the other requirement that’s necessary to make your file truly functional PHP. This other requirement is called the “PHP block,” which is essentially a sort of “container” you would write your PHP in.

There are a few rules we need to follow when coding PHP files. The first is that if we’re coding exclusively in PHP (meaning the entire file is PHP code), we can open the PHP block at the beginning of the file and close it at the end. I’ll give an example of what PHP opening and closing tags look like here:

<?php
    // CODE GOES HERE
?>

The second rule is that if we’re mixing HTML and PHP code in the same file, we’re going to need to open and close PHP blocks multiple times. Here’s an example of that:

<div class="footer-clear"></div>
<footer class="row no-max pad">           
    <p>Copyright <?php echo date('Y'); ?></p>
</footer>
    <?php wp_footer(); ?>
    </body>
</html>

This is some sample code from a footer file in a WordPress theme. What’s important to recognize is the separation of HTML code and PHP code. You can see that it’s PHP code from the opening and closing PHP tags. These are called, “PHP blocks” and may be numerous in number as files get longer.

Remember, if you want to include PHP code in a file, the file has to end in .php. If it ends in anything else, it won’t work. Also, any PHP code needs to be encapsulated inside a PHP block. If it’s not, you’re dynamic PHP code will display as regular text.

Some Basic PHP Syntax

In order to get your PHP functioning correctly, there is some basic syntax that needs to be adhered to. I’ve discussed this in one of my posts on PHP, so if you’d like to read about that, please do so here. Towards the bottom of that post, I get into syntax. If you’d like to read about general PHP development, please take a look at my PHP category.

Filed Under: Development Tagged With: PHP, WordPress


Understanding the WordPress Loop

May 25, 2015

Understanding the WordPress Loop

If you’ve either looked into developing with WordPress or have developed with WordPress for any length of time, I’m sure you’ve heard of the “WordPress Loop.” The loop is one area of WordPress that you don’t want to skimp on. In order to be proficient in development, it’s important to understand exactly what’s going on. With this post, it’s my intention to help out with that. The good news is, it’s fairly straightforward.

To get the most out of learning how to loop works, it’s a good idea to visit the related page in the Codex. It’s here where much of what you’ll need to know is explained.

I think we’ll get started by looking at a small piece of code that’s shown in the Codex:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    // YOUR CONTENT GOES HERE
<?php endwhile; else : ?>
    <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

What you’re looking at above is the bare bones basics of what the WordPress loop can look like. If you’ll notice, there are a few areas and functions in use. I’ll go through things line by line.

In the first line, we have a lot to look at. In this one line, we actually have an if statement, a while statement and the content itself. There are three areas that require consideration.

The first area is an if statement that holds the “have_posts” function and basically asks if there are any posts in existence. If so, then go ahead and continue on to the next area. If not, then jump to the statement that says, “Sorry, no posts matched your criteria.” The have_posts function returns only a yes or no answer and no parameters are allowed.

The second area is a while loop and also uses the have_posts function. This area says that as long as posts continue to exist, then continue on to the next function. If no more posts exist, stop looping.

The last area is used for the content itself and uses the “the_post” function. In the Codex, WordPress says that this function, “Iterates the post index in The Loop. Retrieves the next post, sets up the post, sets the ‘in the loop’ property to true.”

The following lines end the loop and end the if statement.

The above code is one way to write the loop. If you want to see another way, check out this code:

<?php
if ( have_posts() ) {
  while ( have_posts() ) {
    the_post(); ?>
    <h2><?php the_title(); ?></h2>
    <?php the_content(); ?>
  <?php }
}
?>

This might be a bit easier to understand because of the use of the curly braces. You can see more clearly that everything is contained inside the if statement and that the content is contained inside the while loop. But, as you get used to creating and working with the loop, the shorthand that was in the first example is much cleaner to use in your code.

Also, if you’ll notice above, there are a few more functions in use. We already looked at the have_posts and the the_post functions, but we haven’t gone over the “the_title” or “the_content” functions yet.

The the_title function returns the title of the current post. There are a few parameters that you can use inside this function, so if you’re interested in using them, I suggest you read the page in the Codex.

The the_content function displays the contents of the current post and must be used inside the loop. Again, there are a few parameters that you can use here, so if you’re interested, check them out.

To go one step futher, I’m going to build upon my last post and show you some code for how your index page can look. This code should assist in clarifying where you can place your HTML in reference to these PHP functions.

<?php get_header(); ?>
<section class="row">
  <div class="small-12 columns text-center">
    <div class="leader">    
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>    
      <h1><?php the_title(); ?></h1>
      <p><?php the_content(); ?></p>   
  <?php endwhile; else : ?>  
    <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>  
  <?php endif; ?>    
    </div>
  </div>
</section>
<?php get_footer(); ?>

As you can see above, we’ve included the header and footer files. Also in this code is the wrapper code for the loop. So, outside the loop is some HTML for semantics and styling and inside the loop is a heading tag and a paragraph tag to be used for every iteration of content.

I’d like to finish up this post by giving a few references that’ll help make building your template pages and working with the loop much easier. The first one is “The Loop In Action” page in the Codex. By browsing this page, you can find many great code samples that should give you enough ideas to get started.

Also, if you want to work with the loop, you’ll surely want to know some functions that you can use with it. Guess what? There’s a resource for that. It’s the “Function Reference” page in the Codex. Check this one out, but take a few days with it. There’s a lot to go through. Better yet, just put it in your favorites to look back on when you need it.

If you’re interested in going over more WordPress template concepts with me, be sure to take a look at my WordPress category. I write almost every day, so I think you’ll get a lot out of it. I sure am getting a lot out of my learning!

Filed Under: Development Tagged With: PHP, WordPress


Creating & Including WordPress Header & Footer Files

May 24, 2015

Creating & Including WordPress Header & Footer Files

In most WordPress installs (and websites in general) headers and footers are consistent across many pages. Unless there are special sections that are unique to the majority, visitors will see the same layout, with perhaps some dynamic content, at the top of the page and at the bottom of the page. These layouts are pulled into to the page that’s being viewed by two files – header.php and the footer.php.

Now that we have our index.php page set up, we can go ahead and add some code to pull in, or include, the header and footer files to that page. The code to do this would look like:

// INCLUDE HEADER FILE
<?php get_header(); ?>

    // MAIN CONTENT

// INCLUDE FOOTER FILE
<?php get_footer(); ?>

This is the very beginnings of a template page. As you can see, we have both the header and footer files being included by using two WordPress functions. The first one is the “get_header()” function and the next one is the “get_footer()” function. Remember though, it’s important that the header file be named header.php and the footer file be named footer.php. There are more advanced file names than that available, but we’ll talk about them in a later post. For now, focus on these file names.

header.php

This is where the fun starts. We get to begin building the header.php file out. Below, I’ve displayed some very basic code, including some WordPress functions – just to offer an idea of what might be included in the header file. Of course, there is much more that can go inside this file. I merely wanted to show the bare bones. I’ll go over the WordPress functions below.

<!doctype html>
<html class="no-js" lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title><?php wp_title( '|', true, 'right' ); bloginfo( 'name' ); ?></title>
            <?php wp_head(); ?>
    </head>

<body>
    <header>
        <h1><a href="<?php bloginfo('url'); ?>"><?php bloginfo('name'); ?></a></h1>
    </header>

Now, if you’re looking at building WordPress templates, it’s assumed that you have an understanding of HTML, CSS and JavaScript. And since you have an understanding of those things, let’s take a look at what’s above.

At first glance, everything looks like what is normally inside a header file. But since we’re dealing with WordPress and its dynamic nature, we need to use WordPress functions. I suppose you could hard code everything into these files, but if you did that, you’d be missing out on much of the functionality that WordPress offers.

The first function you see above is the wp_title function, along with some parameters. This function displays the titles for all posts and pages on your WordPress site. It looks like this:

<?php wp_title( $sep, $display, $seplocation ); ?> 

As you may be able to guess, as the function sits above, WordPress calls the title of the page, uses a pipe as a separator, displays it and displays it to the right of the title. Which makes sense because to the right of this function is the bloginfo function. This function can look like this:

<?php bloginfo( $show ); ?> 

Now, I’m not going to go over all the available parameters for this function in this post because there are so many of them. If you’re interested in taking a look at what they are, feel free to check out its WordPress Codex page. I will tell you, though, that the bloginfo function parameter that’s showing above will display the site title as is stored in the WordPress admin settings.

The next function – and one that’s quite important – is the wp_head function. This goes right before the closing head tag in the header.php file and fires the wp_head action. Basically, this function calls the functions that we placed in the functions.php file. Due to its very dynamic nature, it’s somewhat confusing to wrap your head around. Just rest assured that the functions you coded into your functions.php file will act as you want them to. Functions such as the wp_enqueue_style and the wp_enqueue_script. In this case, the CSS that you coded earlier will appear in the head section of your header.

Finally, we have two more cases of the bloginfo function. In these cases, we’re simply pulling in the site URL and the name, as we did earlier.

footer.php

Below, we have some code that might be found in the footer.php file. As you can tell, this code is a bit lighter than the header code, but in many cases, you’ll find much more than this.

    <footer>           
        <p>Copyright <?php echo date('Y'); ?></p>
    </footer>
        <?php wp_footer(); ?>
</body>
</html>

Above, we have some simple HTML, along with a few more functions. The first one we see isn’t unique to WordPress. It’s actually the PHP date function. If you want to see how to code this, check out this page.

The last function we have is the wp_footer function. This is found right before the closing body tag. Much like the wp_head function, this one is very dynamic. It generally calls in JavaScript files and if you fail to include it, your JavaScript will not work as intended. A good example of how this might work is through the use of the wp_enqueue_script function (I talked about this in my previous post). If you take a look at the “$in_footer” parameter of the wp_enqueue_script function, you’ll see that it relies on wp_footer. Things in WordPress go round and round like this, so it’s important to really learn how this type of code works and how many areas need one another to give you what you’re looking for.

If you’re interested in more WordPress posts, check out my WordPress category. I’ll be writing many more in the future that cover all types of topics.

Filed Under: Development Tagged With: PHP, WordPress


Internal PHP Functions

May 13, 2015

Internal PHP Functions

I am currently embarking in the final stage of Hampton Paulk’s “PHP Functions” course at Treehouse. It’s been a good one so far. I’ve learned a lot. Hampton has a way of feeding information just slow enough as to be easily absorbed.

In this post, I’m going to go over functions that are internal, or built in, to PHP. Some of these functions come standard with PHP (core functions) and some need to have PHP extensions compiled in.

Function Documentation

The most important area you need to concern yourself with when dealing with internal PHP functions is where to find them and how to parse through the documentation. In this section, we’ll go over exactly how to go about doing that.

Finding Functions

So, where exactly can you find PHP’s internal functions? Well, if you follow this link, you’ll see the “home base” for this area on the PHP site. If you’d like to browse through all the internal function categories on the PHP site, you can visit the Function Reference section.

Reading Functions

On the same page, you’ll see a link that says, ” how to read a function definition” and if you click it, you’ll end up at the “How to read a function definition (prototype)” page. This is where you’ll find the explanation of how exactly to pick apart each area of an internal function.

On this page, you get a pretty good breakdown of a function. The PHP manual explains the function name, the history of the function, what the function returns and parameters/arguments for the function. Although the PHP manual uses only the strlen() function for this example, you can use this as a good guide and apply the same principles across all internal functions.

String Functions

One of the more popular sections of all internal functions are string functions. While this section is widely used, Hampton is going over some of the most popular.

strlen

The first function we’re going to look at is the strlen function. This returns the length of the given string. Let’s go over some code.

<?php
$phrase = "This is my first sentence.";
$len = strlen($phrase);
echo $len;
?>

If we look at the above code, we can see that I created a string and set it equal to a variable called $phrase. Then, I used the strlen function and passed through the $phrase variable as an argument. Since that doesn’t output anything to the screen, I set the strlen function to a variable called $len. Finally, I echoed out the $len variable. For this code, the output is:

26

substr

The next function we’re going to look at is called substr. This function returns part of a string. Let’s look at some code.

<?php
$phrase = "This is my first sentence.";
echo substr($phrase, 0);
?>

If we look at the above code, we can see that I kept the initial string and variable. I changed the other areas though. In the case above, I used the substr function to return the entire string. The way I did this was to pass the $phrase variable to the substr function and then begin the output at the first letter. That’s what the “0” is. It’s the first position in the string. Then, I echoed out the function. In this case, the output is:

This is my first sentence.

Take a look at this next example:

<?php
$phrase = "This is my first sentence.";
echo substr($phrase, 5);
?>

In this example, I changed the 0 argument to 5 and now the string is returned beginning at the fifth character:

is my first sentence.

While the previous example began at the fifth character and continued on to output the remaining characters in the string, this next example begins at the first character again and then only outputs the next five. Here’s the code for that:

<?php
$phrase = "This is my first sentence.";
echo substr($phrase, 0, 5);
?>

The output for this example is:

This

Notice that the fifth character is a space and the rest of the string is truncated.

strpos

The next function we’re going to look at the called strpos. This function finds the position of the first occurrence of a substring in a string. Let’s look at some code.

<?php
$phrase = "This is my first sentence.";
echo strpos($phrase, "first");
?>

In the above code, you can see that I, again, kept the first line the same. After that, I used the strpos function and passed into it the $phrase variable. I also passed part of the string into the function. This part is the word, “first.” Basically, I want to see what character position (in the zero based index) the word “first” resides. In this case, the output is:

11

This means that the first letter in the word “first” resides at the eleventh character position in the entire string $phrase.

Let’s look at one final example that combines the two previous string functions.

<?php
$phrase = "This is my first sentence.";
$start = strpos($phrase, "first");
echo substr($phrase, $start);
?>

Now, don’t let this one confuse you. All we’re really doing here is setting different values to variables and then using those variables to get the output we want. The way to think of this is that we’re making something “equal” to something else.

Again, I kept the first line the same. That’s our string. On the second line of the code, I wanted to find the beginning position of the word “first.” We just went over this. The position is 11. I set that output to a variable called $start. Just with these two lines, we have two variables that “equal” some data. Here they are:

$phrase = This is my first sentence.

$start = 11

Now that we know what the string is and we know what the position of the word “first” is, we can do something with it. In this case, we want to output our string at position 11, or wherever the word “first” starts. The way to do this is to use the substr function we went over above and pass to it the $phrase variable. That’s easy – we just did that above. So, if we left things just like that, our output would be the entire string. We want to output the string beginning at position 11 though, and since we have a variable that’s equal to that position, we simple use that variable as our second argument. So, as the second argument, we insert $start. In this case, our output is:

first sentence.

How cool is that?

Array Functions

The next section of internal PHP functions we’re going to look at is array functions. And more specifically, we’ll be going over the array_keys function and the array_walk function.

array_keys

The array_keys function returns all the keys or a subset of the keys of an array. What the heck does that mean? Let’s take a look at some code to get a clearer picture of what this function can do.

<?php
$names = array(
	"Jay" => "Man",
	"Rob" => "Boy",
	"Russell" => "Manboy"
);
var_dump(array_keys($names));
?>

If we create an array called $names and then var_dump that array using the array_keys function, we get this output:

array(3) { [0]=> string(3) “Jay” [1]=> string(3) “Rob” [2]=> string(7) “Russell” }

This doesn’t mean all too much to us, but if you pick apart the output, you can see that we have three values in our array. For each key, in the square brackets, we get the type of value and the length of the value.

If we want to loop through each key and output a message, we can do so with this code:

<?php
$names = array(
	"Jay" => "Man",
	"Rob" => "Boy",
	"Russell" => "Manboy"
);
foreach (array_keys($names) as $name) {
	echo "Hello $name<br>";
}
?>

This will give us the output:

Hello Jay
Hello Rob
Hello Russell

array_walk

The next function we’re going to go over is the array_walk function. This function applies a user supplied function to every member of an array. Again, we don’t necessarily know what that means, so we’ll look more closely through some code examples.

<?php
$names = array(
	"Jay" => "Man",
	"Rob" => "Boy",
	"Russell" => "Manboy"
);
function print_info($value, $key) {
	echo "$key is a $value.<br>";
}
array_walk($names, print_info);
?>

In the code example above, we’re using the same array as above. For the second code block, I created a function called “print_info” and passed through, two values. The first is a variable called $value and the second is a variable called $key. Inside the function, we simply echo out a sentence that says, $key is a $value.

In order to pass through those two variables, we’ll use the array_walk function to go through each key/value pair one at a time. Inside the array_walk function, we’ll pass through our array called $names and the our callback, which is the print_info function itself. We’ll get this output:

Jay is a Man.
Rob is a Boy.
Russell is a Manboy.

I’m not going to lie to you here when I say this one is a bit confusing. I’m still trying to wrap my head around the $key variable. I’m not sure if that’s something that’s internal to PHP and this function. I’m also not sure how it was created. I’ll have to look into it more. If you have any thoughts, please let me know in the comment section below. From that I’m gathering from other sites, it seems like it’s just “there.”

Well, that brings us to the end of Hampton’s “PHP Functions” course on Treehouse. I learned a lot here and really gained an understanding of it by writing it all down. I’m sure that last part about the $key variable will gnaw at me for some time until I figure it out, but otherwise, great course.

If you have any questions about this post, please ask in the comment section below. If you would like to check out some of my other PHP posts, please click the PHP link at the top of this page.

Filed Under: Development Tagged With: PHP


PHP Function Returns

May 7, 2015

PHP Function Returns

Today, I’m going to continue on with my interpretation, or should I say – basically – my notes, on Hampton Paulk’s “PHP Functions” class over at Treehouse. I’ve been enjoying Hampton’s style and his teaching is remarkably understandable.

In this post, I’m going to go over PHP function returns. Now, before I started writing today, I did a little Google search for the title of this post and nothing immediately popped up. Something called, “Returning Values in PHP” was returned, but obviously, that doesn’t precisely hit the mark. I’ll have to see where he’s going with this one. With that said, let’s dive into it.

PHP return Statement

What we’re talking about here is the return statement in PHP. I found a few definitions of this statement and listed them below. Here they are:

PHP.net

“Values are returned by using the optional return statement. Any type may be returned, including arrays and objects. This causes the function to end its execution immediately and pass control back to the line from which it was called.”

W3Resource

“PHP return statement immediately terminates the execution of a function when it is called from within that function. This function is also used to terminate the execution of an eval() function or script file. If this function is called from global scope, the function stops the execution of the current script. If the current script file was included using include() or required(), then control goes back to the calling file.”

Hampton basically says that by having a function return a value, we’ll be able to store data from a function call to any type of a value variable. He says the return statement will immediately end the function’s execution as well, returning control back to where the function call resides. So, as you can see, I think I’m on the right track with this one. Hampton’s definition is in line with the other two I listed above.

Now that that’s out of the way, let’s get into some code examples so we can see what these return statements look like. And as usual, I’ll mix these examples up as to make them my own. I like to stretch the imagination. Also, if you’re practicing your own PHP and would like to play around and run these examples, you can do just that over at Runnable. That’s where I test out my PHP code online.

Regular Return

<?php
function test() {
    return "This is the function output.";
}

$output = test();

echo $output;
?>

In the above code, we’ve got a few things going on. First, we’ve got a function. You’ve seen those before from my previous post about PHP functions. The thing is, inside this function, we’ve got one of those “return” statements, instead of an “echo” statement. So, like I said above, by using the return statement, we can store the function output value inside a variable. That’s what we’re doing above – storing the string inside a variable called, “$output” that’s outside the function. Lastly, we’re now echoing the variable, which gives us the ultimate output of:

This is the function output.

Pretty cool.

If we wanted to throw an if/else statement into our function, we could do that like this:

if/else Statement

<?php
function test($input) {
    if($input == "One") {
        return "This is the first function output.";
    } else {
        return "This is the second function output.";
    }
}

$output = test("One");

echo $output;
?>

In this case, the output would be:

This is the first function output.

If we included anything other than “One” when we called the function, the output would have been:

This is the second function output.

Here’s a fun one. It’s going to take some more looking at, but I think it’s rather straight forward.

Calculating Integers

<?php
function sum($x, $y) {
   return $x + $y;
}

$total = sum(5, 9);

echo $total;
?>

In the above code, I created a function called “sum” that allows two arguments. Inside the function, I’m adding the arguments and returning them outside the function. Outside the function, I’m passing the function two integers – in this case – 5 and 9 and storing the result of them in a variable called $total. Finally, I’m echoing the $total variable and in this case, the output is:

14

I do want to point out one strange occurrence. In the video I’m watching with Hampton, he said that he couldn’t name his function “sum” because it’s an “internal word.” Therefore, he named his “add_up” instead. I thought that sounded peculiar because I’ve seen other functions with the name of sum and they worked fine. I went ahead and named mine sum as well and it works. I’m wondering it Hampton avoided this word out of safety or if it was based on something I’m missing. I’ll have to look into this later on.

Not Storing in a Variable

I was looking through W3Schools and came across an example of adding and returning integer values. It’s different because in the example they gave, they don’t store anything in a variable. Here, take a look at the example:

<?php
function sum($x, $y) {
     $z = $x + $y;
     return $z;
}

echo "5 + 10 = " . sum(5,10) . "<br>";
echo "7 + 13 = " . sum(7,13) . "<br>";
echo "2 + 4 = " . sum(2,4);
?>

The result of this is:

5 + 10 = 15
7 + 13 = 20
2 + 4 = 6

I went ahead and changed the code around to look like this:

<?php
function sum($x, $y) {
     $z = $x + $y;
     return $z;
}

$total1 = sum(5,10);
$total2 = sum(7,13);
$total3 = sum(2,4);

echo "5 + 10 = " . $total1 . "<br>";
echo "7 + 13 = " . $total2 . "<br>";
echo "2 + 4 = " . $total3;
?>

I got the same exact result, which just goes to show, there’s more than one way to skin a cat.

Using print_r

In this next example, we’re going to pass in two integers to our function, create an array inside the function and then return the array. We’ll use the print_r function to output the information about the array.

<?php
function sum($x, $y) {
    $arr = array(
        $x,
        $y,
        $x + $y
    );
    return $arr;
}

$total = sum(5, 9);

print_r($total);
?>

The output for this function is:

Array ( [0] => 5 [1] => 9 [2] => 14 )

If you aren’t aware of what the print_r function is, it’s one of PHP’s internal functions that displays human-readable information about a variable. In the case above, the variable is called “$arr” and has the array stored in it. If we didn’t use the print_r function and simply went ahead trying to echo our result, like we did in the previous examples, the output would have been “Array.”

Now, looking a bit closer at the output for the above example, it’s important to note that what’s output for this array is the key (position in the array) and the result for each line inside the array. So, what we have above is key 0 with the result of 5, key 1 with the result of 9 and key 2 with the result of 14.

I’m not sure the previous output is entirely useful, so let’s take a look at how to pull out just one line, or key position in this above array. Take a look at the following code:

<?php
function sum($x, $y) {
    $arr = array(
        $x,
        $y,
        $x + $y
    );
    return $arr;
}

$total = sum(5, 9);

echo $total[2];
?>

Notice how the last line is changed. Instead of:

print_r($total);

We’ll use:

echo $total[2];

To output just the third key position in the array. In this case, the output is:

14

Variable Functions

This section sort of threw me when I watched the movie on Treehouse. I’m not sure enough information was given as background as to why I would want to use a variable function. And as I write this, I’m still not sure what a “callback” is or how it would be helpful. But Hampton hasn’t let me down yet, so I’ll give him the benefit of the doubt when he says, “We’ll go over callbacks in a later lesson.”

For now though, I’m going to take his example, just the way he wrote it and copy it here. Then, I’m going to attempt to make sense of it as I type. Here goes.

<?php
function answer(){
    return 42;
}

function add_up($a, $b){
    return $a + $b;
}

$func = "answer";

echo $func();
?>

Okay, so this is his first example. What we’re doing here is using only the first function called “answer.” Towards the bottom, we’re creating a variable and calling the function by using a string called “answer.” I’ll admit, this is where it gets confusing. I understand how this is working – in this case, the string is the name of the function, but what happens if we really wanted to store a string of text called “answer” in a variable? Would it still call the function? I’m sure I just haven’t learned something yet.

Perhaps the next line gives us more information. From what I’m gathering, the variable called $func is simply set to a string called “answer.” That’s really just a string. It doesn’t turn into anything special until you add an open and closed parenthesis after the variable. It’s only then that the string inside that variable comes alive and calls the function. Does that make sense?

Let’s go over this one more time. Right here, we have a function called “answer.”

function answer(){
    return 42;
}

And here, we have a simple string of text called “answer” set to a variable named $func. This is straightforward and as of right now, still just a string.

$func = "answer";

Finally, we can call the “answer” function, by first calling the string inside the $func variable. We’ll do this by adding two parenthesis after the $func variable and echoing it. It’s that simple

echo $func();

And for this whole example, we get the output of:

42

We get this because really, all the initial function did was return that value.

Boy, that was confusing, but I think I get it now.

Hampton gives another example. Here it is:

<?php
function answer(){
    return 42;
}

function add_up($a, $b){
    return $a + $b;
}

$func = "answer";

$num = $func();

echo $num;
?>

There really isn’t much changed here. All he did was set the $func() call to a variable called $num. Then, he echoed the $num variable and got the same result, which is:

42

But wait, there’s more. Take a look at this next example:

<?php
function answer(){
    return 42;
}

function add_up($a, $b){
    return $a + $b;
}

$func = "add_up";

$num = $func(5, 10);

echo $num;
?>

In this example, all we did was change the string in the $func variable to the name of the next function, which is “add_up.” Now, by calling the $num variable at the bottom, we’re calling the $func variable with the newly placed arguments right above it, which in turn, calls the $func variable with the string of “add_up” right above that, which in turn, calls the function called “add_up” and passes two values into it to add up. For all this work, we get the output:

15

Hampton promises this is very handy. Again, we’ll go over why in later lessons. For now, I think I’ll I’ll just tuck it in the back of my mind somewhere to use at a later date. I do get it though, and I guess that’s the most important. If you’d like to read up on variable functions in your free time, please feel free to browse through this page.

PHP Closures

Do you know what a PHP closure is? Well, if you don’t, please read this:

Hampton

“Closures are anonymous functions, which are functions with no name, that are capable of accessing variables outside of the function scope.”

PHP.net

“Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.”

Closures seem to simply be a function that’s set to a variable that has special powers. Before we get into those powers, let’s look at what an anonymous function that’s set to a variable looks like:

<?php
$greet = function(){
    echo "Hello there.";
};

$greet();
?>

In the first line, we have a variable named “$greet” and that’s equal to an anonymous function. Inside the function is a simple string that will be echoed when the function is called. Below the function, we have the function call. The output for this is:

Hello there.

Now it’s time to spice things up a bit and talk about the special powers of a closure. Typically, functions can’t access variables that are set outside of the function in question. This is called being outside of the function “scope.” When dealing with a closure though, we can take advantage of a keyword called “use” that allows us to go outside of a function and grab a variable and then pull that variable back inside the function. Take a look at this example:

<?php
$name = "Jay";

$greet = function() use($name){
    echo "Hello $name.";
};

$greet();
?>

As you can see, we created a variable that’s outside of the function scope. This is a variable named “$name” and it’s equal to Jay. In order for the function to access this variable, we wrote the keyword “use” and then parenthesis with the variable $name inside of it. The “use” is instrumental in allowing the usage of the outside variable. Then, inside the function, we take advantage of the $name variable and echo out:

Hello Jay.

This seems more straightforward than the last section, but they were all fun.

Unfortunately, this is the end of this post. If you have any comments or questions (or advice), please leave everything down in the comment section below.

Filed Under: Development Tagged With: PHP


Working With PHP Functions

May 1, 2015

Working With PHP Functions

In this post, I’m going to talk about working with functions in PHP. In order to do that though, I think we should first get a working definition of what exactly a function is.

Much like in other programming languages, a function in PHP is a section of code that receives input, completes a set amount of processing and then returns a value. It’s actually not a difficult concept to grasp once you get some practice. That’s what I intend to do with this post.

Overview of PHP Functions

In order to get used to what a function looks like, I think we should write one. Take a look at the following code. Below it, I’ll give a bit of explanation as to what’s going on.

<?php 
function hello() {
    echo 'Hello World!';
}

hello();
?> 

In the above code, we’ve got a few things going on. Of course, we have our opening and closing PHP tags. That’s a given. After the opening PHP tag, we have the word “function.” This word is a declaration that tells the PHP interpreter on the server that what’s after it is indeed, a function. After the word “function” is the actual name of the function. In this case, the name of the function is the word “hello,” followed by an opening and closing parenthesis. After the name of the function and parenthesis, we have opening and closing curly braces. Those curly braces surround the part of the code that’s going to actually execute when the function is called. The way to call a function – in this case, the function called “hello” – is to simply write the name of the function, followed by the two parenthesis. After that, close the statement with a semicolon. For the function above, we have the output:

Hello World!

If you’d like to copy and paste the above code to see how it works, you can do so at Runnable.

Now, there are a few things about functions that I think I should tell you. Here they are:

– There are over 1000 built in PHP functions.

– We can either use the built in functions or create our own – or both.

– Once we create a function, we can use it repeatedly in a program.

– PHP functions don’t just run by themselves every time someone loads a page. They need to be “called.”

– When the function is called, the code inside of it will be executed.

– When we’re creating a function ourselves, we begin the code with the word “function.”

– To name a function, we can use either a letter or an underscore – not a number.

– When naming functions, be kind to fellow coders and give it a name that means something.

Let’s write another function:

<?php
$myName = 'Jay';

function name() {
    global $myName;
    if ($myName == 'Jay') {
        echo 'Hey, that is my name!';
    } else {
        echo 'No way man. That is not my name!';
    }
}

name();
?> 

This is a fun one. In the above code, I’ve added a few areas to spice up life a bit. Let’s start at the top. In the first line, I created a variable called, $myName. I set that variable to a string called, “Jay.” That’s my name. After that, we start writing our function.

This time, I decided to call our function “name.” I set the function up with the same code as I did last time, but this time, the insides are a bit different. As you can see, once inside the function, I used the word “global” and typed the name of the variable after it. The reason I did this has to do with something called “scope.” While that’s a topic for a different time, I will tell you that since I declared my variable outside of the function, it has a global scope and can only be used outside of the – well, function. In order to use that variable inside the function, I needed to use the keyword, “global.” That allows me to use a global variable inside a function. It’s a neat way to bend things to the way I need them.

Now, after the global keyword and the name of my variable, you can see that I created an if/else statement. Inside that statement, I basically said, “If my name is Jay, then output, “Hey, that is my name!.” If it’s not, then output, “No way man. That is not my name!”

Lastly, below the function, I called it. In this case, since the variable I declared up at the top does contain the string “Jay,” the output is:

Hey, that is my name!

If I put any other word in the variable or left it blank, the output would be:

No way man. That is not my name!

Arguments in PHP

In this section, I’m going to start making our PHP functions a bit more dynamic. This means that I’ll be using something called, “arguments.” In PHP, arguments are sort of like variables, in that you can declare them in one place and they can be used in another. If you’d like to use an argument in your function, you need to tell the function what it is by specifying it between those two parenthesis we use after the function name. You can even have more than one argument as long as you use a comma in between each one of them.

Let’s take a quick look at some more code. This time, I’m going to use an argument.

<?php
function hello($name) {
    echo "Hello $name!";
}

hello("Jay");
?> 

In the above code, you can see something that looks almost like our very first example. The only thing that’s different is that I filled the parenthesis after the function name with an argument. This one is called, $name. If you look inside the function, you can see that we use that argument in the string output. Lastly, when we call the function, we pass through my name, so the output we get from this function is:

Hello Jay!

Let’s say that we want to say hello to a bunch of people, but don’t want to write the function over and over again. We can do this fairly easily. Take a look at this code:

<?php
function hello($name) {
    echo "Hello $name!<br>";
}

hello("Jay");
hello("Bob");
hello("Roger");
hello("Beth");
hello("Mary");
?> 

In the above code, all I did was to add an HTML line break after the echo output inside the function and then copy/paste our function calls with a few different names. Take a look at the output of this one:

Hello Jay!
Hello Bob!
Hello Roger!
Hello Beth!
Hello Mary!

Pretty neat, huh? And if we wanted to change any of the outputted names, all we’d have to do is change them when we’re calling the function.

There is a different way to do this though. The function is a bit more complex, but in the long run, you’d save yourself some typing by creating an array for multiple values being passed into a function. Here, take a look:

<?php
function hello($arr) {
    if(is_array($arr)) {
        foreach($arr as $name) {
            echo "Hello $name!<br>";
        }
    } else {
        echo "Hello world!";
    }
}

$names = array(
    "Jay",
    "Bob",
    "Roger",
    "Beth",
    "Mary"
);

hello($names);
?> 

If you look towards the bottom of this code, you’ll see that I created an array named, $names. Inside the array, I used the same names I used for the previous example. The only difference is that I put the names inside an array as opposed to writing them each on their own line. After the array, I called the function using the array as the argument.

The first thing I did in the function was to check to see if we were looking at an array. I did this by using the “is_array” function that’s built into PHP. This function checks to see if a variable is an array or not. If an array has been passed to the function, the output will be the greeting for the list of names, just like we did in the last example. If something other an an array has been passed to the function, then the output will be “Hello world!”

Let’s assume an array has been passed to the function. In this case, we need a way to cycle through the array and output each greeting and name. For this, we used the foreach loop that I talked about in my previous PHP post (the loop that’s used for arrays).

So, if we run this code, we’ll get the output:

Hello Jay!
Hello Bob!
Hello Roger!
Hello Beth!
Hello Mary!

Now that seriously is neat!

Default Arguments in PHP Functions

Let’s say that you’re interested in allowing an argument to be passed to a function, but you aren’t sure if one is always going to be passed. There’s a way to set up your function to allow for this. Take a look at this code:

<?php
function namePlace($name, $place) {
    echo "My name is $name and I live in $place.";
}

namePlace("Jay", "Maine");
?>

If we run this function, the output will be:

My name is Jay and I live in Maine.

This is expected. It’s the same type of function that we’ve been running throughout this post.

Now, what if we, for some reason or another, don’t pass the second argument to the function? If we have code like this:

<?php
function namePlace($name, $place) {
    echo "My name is $name and I live in $place.";
}

namePlace("Jay");
?>

Our output will look like this:

My name is Jay and I live in .

For obvious reasons, we don’t want this to happen. To solve this problem, we can use what’s called a default argument. What’s a default argument? Well, simply put, it’s when you set an argument in a function to a default value, for that value to appear in the case an argument isn’t passed to the function when the function is called. Let’s set up a default argument in this next code example:

<?php
function namePlace($name, $place = "a very special place") {
    echo "My name is $name and I live in $place.";
}

namePlace("Jay");
?>

If you look at the above code, you’ll see that we’re not passing an argument for $place again, but this time, we set a default argument. Now, if we run this code, this will be the output:

My name is Jay and I live in a very special place.

But what if we have our function set up with a default argument, but decide to pass one for that value as well? Well, that would look like this:

<?php
function namePlace($name, $place = "a very special place") {
    echo "My name is $name and I live in $place.";
}

namePlace("Jay", "Maine");
?>

The really cool thing about default arguments is that they fall by the wayside and are overridden if an argument is passed. So in the case of the above code example, our output would look like this:

My name is Jay and I live in Maine.

See how the “Maine” argument overrode the default argument of “a very special place”?

Now, if you’d like to make passing an argument optional, then all you have to do is set your default argument to null and write an if/else statement. Take a look at this code:

<?php
function namePlace($name, $place = Null) {
    if($place) {
        echo "My name is $name and I live in $place.";
    } else {
         echo "My name is $name.";
    }
}

namePlace("Jay", "Maine");
?>

As you can see, I set the default argument of the $place variable to Null. I also wrote an if/else statement that says, if the $place argument is passed, then echo this response. If it isn’t passed, then echo this response instead. So, in the above code, since the $place argument was passed, our output is:

My name is Jay and I live in Maine.

And if it’s not passed, then the output would be:

My name is Jay.

Talk about flexibility!

Well friends, this is the end of another action packed post. If you’re interested in learning more about PHP, be sure to check out my PHP category. Thanks!

Filed Under: Development Tagged With: PHP


Conditional Statements & Loops in PHP

April 23, 2015

Conditional Statements & Loops in PHP

For this last section of my PHP series, I’m going to discuss conditional statements and loops in PHP. These two areas truly are at the heart of this programming language, so it’s important to get a solid understanding of what they do and how they work.

Conditional Statements

In the most basic sense, conditional statements test things. If this is bigger than that, then do this. If this isn’t bigger than that, do something else. With these types of statements, you can execute various actions based on a variety of conditions.

We have four different types of conditional statements in PHP and I’ll discuss each one of them below. But first, let’s look at the different types of statements.

if – if your condition is true, then the code inside the statement is run.

if/else – if the first part of your condition is not met, then the next part of your code is run.

if/elseif/else – in this sequence of events, if your first condition is met, your code runs. If the first condition is not met, a second condition is challenged. If that is met, then the second chunk of code runs. If both the first and second conditions aren’t met, then the final section of code is run.

switch – with this statement, you can compare something to a series of conditions. If one is met, the statement will break and exit. If nothing is met, the default condition will run.

if Statement

The first conditional statement we’re going to look at is the if statement. This is the most simple of all PHP conditional statements.

if (condition) {
    // code to be executed if condition is true;
}

If you look at the code above, you’ll see the layout of how this conditional statement works. Like I mentioned above, if a condition is found to be true, then the code inside the curly braces is run. Let’s look at a functioning example.

<?php 
 define("USE_FULL_NAME", TRUE);
 
 $first_name = "Jay";
 $last_name = "Gaulard";
 
 if( USE_FULL_NAME == TRUE ) {
 	$name = $first_name . " " . $last_name;
 }
 
 echo $name;
 ?>  

In the above code, I defined USE_FULL_NAME as true. After that, I created two variables. The first one is for my first name and the second one is for my last name. I could have left these out, but I wanted to make things more interesting and to build on previous posts. After that, I wrote my if statement. In this statement, I tested whether or not my initial definition (USE_FULL_NAME) was true or not. Since it was, the code inside the conditional statement was run. In this code block, I created a new variable by concatenating the first two variables I created outside the conditional statement. Lastly, I echoed out the new variable to make sure everything was coded correctly. It was and the output was “Jay Gaulard.”

Next up, we’re going to see what happens if our constant is declared false by using an if/else statement.

if/else Statements

Let’s say that, for some reason or another, our USE_FULL NAME constant was defined as false. If this is the case, then our initial if statement would return nothing, instead of my name. But what if we wanted it to return something instead of nothing? Well, in this case, we can use an else statement.

<?php 
define("USE_FULL_NAME", FALSE);

$first_name = "Jay";
$last_name = "Gaulard";

if( USE_FULL_NAME == TRUE ) {
	$name = $first_name . " " . $last_name;
} else {
	$name = $first_name;
}

echo $name;
?> 

As you can see, the initial constant is now defined as false, so we do not want to use our full name anymore. So in this case, instead of returning nothing, I used an else statement to return just the first name. The output of this conditional statement is now just “Jay.”

Just as a reminder, like I did in my previous PHP post, I’m again using Runnable to test out my PHP code before I copy it over here. Just to make sure it works as I intend it to.

if/elseif Statements

If we want to test something and then test something else if the first test fails, we can use if/elseif statements. I’ll give you an example of what that looks like below.

<?php 
define("USE_FULL_NAME", TRUE);

$first_name = "Jay";
$last_name = "Gaulard";
$role = "JiuJitsu";

if( USE_FULL_NAME == TRUE ) {
	$name = $first_name . " " . $last_name;
} else {
	$name = $first_name;
}

if( $role == "Woodsman" ) {
	$info = "I am a Woodsman living in Maine";
} elseif( $role == "JiuJitsu") {
	$info = "I practice Jiu-Jitsu in Maine";
} else {
	$info = "I am just a regular guy living in Maine";
}

?>

Hi. My name is <?php echo $name ?> and <?php echo $info ?>.

In the above code, I changed the first constant back to true, so my full name will be used in this example.

As you can see, I added another variable up top. This variable sets my role. I can either be a Woodsman or a JiuJitsu practitioner. If I am anything else, I have some default text to show that I’m just a regular guy. Let’s take a look at how this code operates.

In the second code block, I have an if statement that asks if my role is a Woodsman. If it is, then the final output all the way at the bottom of the code will return this line:

“Hi. My name is Jay Gaulard and I am a Woodsman living in Maine.”

If my role is not a Woodsman and is set to JiuJitsu instead, the final output would be:

“Hi. My name is Jay Gaulard and I practice Jiu-Jitsu in Maine.”

Finally, if my role is neither of these or if the role variable is left blank, the default output would be this:

“Hi. My name is Jay Gaulard and I am just a regular guy living in Maine.”

This is a pretty good example of how if/elseif/else statments work in PHP.

Loops

PHP recognizes four different types of loops. I’ll give short definitions of them below and then play with some code after that. First though, let’s talk about what a loop actually is.

A loop in PHP is an executable piece of code that is able to run through itself again and again. You can set the loop to run a specific number of times and create arguments that guide what the loop actions are to obey.

Now, to look at those types of loops:

for loop – loops through block of code the number of times you specify. Here is an example of the setup of this type of loop:

for (expr1; expr2; expr3) {
    statement
}

while loop – loops through block of code if/while condition is true. Here is an example of the setup of this type of loop:

while (expr) {
    statement
}

do-while loop – loops through block of code one time and will only repeat if condition is true. Here is an example of the setup of this type of loop:

do {
    statement
} while (expr)

foreach loop – loops through block of code for each element in an array. Here is an example of the setup of this type of loop:

foreach (array_expression as $value) {
    statement
}
foreach (array_expression as $key => $value) {
    statement
}

for Loops

I’m going to give some example code of a real working for loop in PHP. I’ll write the code and then talk about it below.

<ul>
<?php
for( $counter = 0; $counter < 10; $counter++ ) {
	echo "<li>" . $counter . "</li>";
}
?>
</ul>

If you look at the above code, you’ll see a working for loop. Inside the loop are three expressions. Here’s how these expressions work:

“The first expression is evaluated (executed) once unconditionally at the beginning of the loop. In the beginning of each iteration, the second expression is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.”

So above, the first expression is a counter. That’s always evaluated. Initially, I have it set to 0. After that’s evaluated, the second expression is evaluated. In this case, if the counter value is less than 10, the loop will continue on to the third expression. In this case, this is an incrementer. It adds 1 to the counter variable every time it’s executed. The output of this loop is:

0
1
2
3
4
5
6
7
8
9

Now, if we wanted the loop output to begin at 1 and end at 10, we’d simply adjust the expressions in the loop. An example of that would be:

<ul>
<?php
for( $counter = 1; $counter <= 10; $counter++ ) {
	echo "<li>" . $counter . "</li>";
}
?>
</ul>

The output of this loop would be:

1
2
3
4
5
6
7
8
9
10

Let’s say that we wanted to have some control over this loop via a defined constant. If we change the constant, our loop will change. Take a look at this code:

<ul>
<?php
define("MAX_COUNTER", 20);

for( $counter = 0; $counter <= MAX_COUNTER; $counter++ ) {
	echo "<li>" . $counter . "</li>";
}
?>
</ul>

In the above code, I added a constant and set it to 20. Then, in the loop, I adjusted the second expression to tether to the constant. You can do this with variables as well. The output of the code would be:

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

foreach Loops

Foreach loops are really powerful and quite useful. They are able to loop through arrays, so any time you have multiple items and relatively duplicate sections of code, you can apply a foreach loop to handle the repetitiveness with ease. While I’m not going to give any examples of in-depth HMTL code here, I will give you a simple example of how a foreach loop functions. Take a look at the code below:

<?php

$names = array( "Jay", "Pete", "Rob", "Gary", "Russell" );

foreach( $names as $name ) {
	echo $name . "<br>";
}

?>

In the above code, I first created an array in PHP. That array consists of five names – mine and four of my friends. The loop I created below simply loops through the array and outputs the names I included. Here’s the output:

Jay
Pete
Rob
Gary
Russell

If I wanted to change the output, I would simply change the values in the array.

To dig deeper into exactly how PHP handles these types of loops, you can read up here. I will give you a quick breakdown here though:

“This type of loop loops over the array given by $names. On each iteration, the value of the current element is assigned to $name and the internal array pointer is advanced by one (so on the next iteration, you’ll be looking at the next element).”

Pretty simple, right?

Well, this is the close of another fun filled post on PHP. To continue reading, be sure to check out my PHP category.

Filed Under: Development Tagged With: PHP


Operators in PHP

April 18, 2015

Operators in PHP

In PHP, operators are used to manipulate or perform operations on variables and values. And just like other programming languages, there are quite a few operators. These operators can be grouped under specific headings to help keep things a bit more organized. I’ll go over each group below. Before I begin though, I thought I’d cover the three major types of operators.

The first type of operator is called, “unary.” A unary operation is an operation with only one operand. Examples of a unary operator are the + or the – operators.

The second type of operator is called, “binary.” A binary operator consists of two unary operators combined as one. Examples of this are >= or the <=. The third type of operator is called, “ternary.” Ternary operators use three operators to accomplish its task. Examples of these are the === to test the equality and type of two values, while just the == tests the equality.

Groups of PHP Operators

We can arrange PHP operators into a few groups. These groups are as follows. I’ll go over some of these in more detail below.

Arithmetic operators – Used with numeric values to perform operations. Addition, subtraction, multiplication, division. (+, -, *, /, %, **)

Assignment operators – Used to assign values to variables. (=, +=, -=, *=, /=, %=, .=)

Comparison operators – Used to compare two values. (==, ===, !=, <>, !==, >, <, >=, <=) Increment/Decrement operators – Used to increment or decrement a variable’s value. (++, –)

Logical operators – Used when combining conditional statements. (and, or, xor, &&, ||, !)

Array operators – Used when comparing arrays. (+, ==, ===, !=, <>, !==)

String operators – Used to either concatenate two arguments or to concatenate and assign the right argument to the left. (., .=)

Playing With Operators in Code

In this section, I’m going to go over some examples of how operators are used in real code. While these are fairly simple examples, they’ll give a good idea of what these operators look like and how they can function.

Arithmetic & String Operators

When learning PHP, the first operators people go to are the arithmetic operators. These are straightforward and make for some mighty nice understanding. Let’s write some code.

<?php
$a = 50;
$b = 25;

$add = $a + $b;
$subt = $a - $b;
$mult = $a * $b;
$div = $a / $b;

echo $add . "<br>";
echo $subt . "<br>";
echo $mult . "<br>";
echo $div . "<br>";
?>

As you can see in the example above, the first things I did was to assign the values of 50 and 25 to the variables $a and $b respectively. After that, I performed some operations on those variables. First, I added them together. Then, I subtracted them. After that, I multiplied them and finally, I divided one into the other. In the last part of the code, I echoed out the results using the concatenation operator and some HTML for line breaks. In this case, the output would be:

75
25
1250
2

If you’re interested in running the above code yourself, you can do that with a tool I use over at Runnable.

Increment & Decrement Operators

The next area we’re going to look at is incrementing and decrementing. Check out the code below.

<?php
$a = 50;
$b = 25;

$add = $a + $b;
$subt = $a - $b;
$mult = $a * $b;
$div = $a / $b;

$add++;
$subt++;
$mult++;
$div++;

echo $add . "<br>";
echo $subt . "<br>";
echo $mult . "<br>";
echo $div . "<br>";
?>

I used the same code from the example above and simply added an auto-increment to each variable after its assignment. In this case, the output would be this:

76
26
1251
3

If I did the same thing, but added an auto-decrement to each variable like this:

<?php
$a = 50;
$b = 25;

$add = $a + $b;
$subt = $a - $b;
$mult = $a * $b;
$div = $a / $b;

$add--;
$subt--;
$mult--;
$div--;

echo $add . "<br>";
echo $subt . "<br>";
echo $mult . "<br>";
echo $div . "<br>";
?>

Our output would look like this:

74
24
1249
1

Comparison Operators

In this section, we’re going to go over some comparison operators. Before we begin though, I’d like to cover a function that I’m going to use to help out with some of the variables we’re going to compare. The function is called var_dump() and is used to display structured information (type and value) about one or more variables. It’ll become more clear below as to how exactly this is useful.

In the following code, I’m going to show you some comparison operators and after that, I’ll go over them.

<?php
$a = 50;
$b = 50;
$c = 75;
$d = "50";

var_dump( $a == $b ); // equal (value)
var_dump( $a != $b ); // not equal (value)
var_dump( $a === $b ); // identical (value and type)
var_dump( $a !== $d ); // not identical (value and type)

var_dump( $a < $b ); // less than
var_dump( $a > $b ); // greater than
var_dump( $a <= $b ); // less than or equal to
var_dump( $a <= $c ); // greater than or equal to
?>

If we run the above code, we’ll see the output is this (I’ll give an explanation next to each one):

bool(true) – a is equal to b
bool(false) – a is equal to b
bool(true) – a is identical to b
bool(true) – a is not equal to d

bool(false) – a is equal to b
bool(false) – a is equal to b
bool(true) – a is equal to b
bool(true) – a is less than c

As you can see, the var_dump() function is outputting the type of statement we’re running, along with the value of its output. In the first line above, the output is bool(true) because a is, in fact, equal to b. The second line is false because a is equal to b. It’s not not equal. The third line is true because a is identical in type and value to b, while in the fourth, the value is true because a is not equal in type and value to d.

In the second set, the first line is false because the question asks, is a less than b? a is equal to b, so this is false. On the second line, the same thing is happening – a is equal to b, so it can’t be greater than it at the same time. On the third line, since a is equal to b, the output is true and on the fourth line, we get a true because a is less than c.

Logical Operators

If we use the var_dump() function some more for testing, we can play around with some logical operators. In the code below, I’m going to test to see if a and b are true.

<?php
$a = TRUE;
$b = TRUE;

var_dump( $a and $b );
?>

The only way the output of this statement can be true is if both the values of the variables a and b are true as well. Since they are, the output we get is:

bool(true)

Now, if we run the following code:

<?php
$a = TRUE;
$b = FALSE;

var_dump( $a and $b );
?>

We’ll get this output:

bool(false)

Because the value of a and b are different. b is not false.

I’ll write some additional code below to give some examples of more logical operators. To mix things up a bit, I’ll give a short explanation right next to each statement.

<?php
$a = TRUE;
$b = FALSE;

var_dump( $a and $b ); // returns true if a AND b are true
var_dump( $a or $b ); // returns true if a OR b are true
var_dump( ! $a ); // returns true if a is NOT true
var_dump( $a && $b ); // returns true if a AND b are true
var_dump( $a || $b ); // returns true if a OR b are true
?>

The output of this code would be:

bool(false) – a and b are not true
bool(true) – a is true
bool(false) – a is true
bool(false) – a and b are not true
bool(true) – a is true

So there we have some coverage of various operators in PHP. I’m going to go through all of these in greater detail in the future. To keep tabs on this, take a look at my PHP category.

Filed Under: Development Tagged With: PHP


PHP Data Types

April 10, 2015

PHP Data Types

Do you remember back when I talked about variables in PHP? If not, you really should check out my post as I covered a lot of ground. If you don’t have the time, I’ll give you a very quick refresher here.

Variables are containers to store data. It’s like you carve out spaces in your computer’s or server’s memory for your variables to reside. When you’re ready, you can add data to those variables, basically filling the containers. It’s the data, and what those types of data are, that we’re going to talk about in this post. But really, check out my PHP post to get some background. You can even browse the “Variables” section of my latest JavaScript post as I go over very similar information in that post as well.

Data Types

There are multiple data types in PHP that offer ways for variables to store data. I’ll list them here:

– Strings (strings of characters)
– Integers (whole numbers)
– Floats (fractional numbers)
– Booleans (true or false objects)
– Arrays (stores multiple data types)
– Objects (the root of object-oriented programming – complex variables)
– NULL (represents a variable with no value)
– Resources (not PHP data – reference to functions / resources external to PHP)

To read about PHP data types right from the source, you can check out the page in the PHP Resource.

Now that I’ve shown the PHP data types, let’s go over some of these in more detail.

Integers

Integers are simply whole numbers. They can be positive or negative, but can’t contain decimal points. An integer must contain at least one digit and include no spaces or commas. Integers can be specified as decimal, hexadecimal, or octal.

I’m going to show you a working example of integers in PHP.

<?php
$one = 1; 
$two = 2;
$three = 3;

echo $one;
echo $two;
echo $three;
?>

On a web page, the output of these three “echos” would be:

1
2
3

That’s pretty simple.

There is a confusing area surrounding integers in PHP, though, and this area is when you enclose your integers in quotes. So, if we use the same example from above, but surround the last variable in quotes, we should see this:

<?php
$one = 1; 
$two = 2;
$three = "3";

echo $one;
echo $two;
echo $three;
?>

The output would be this:

1
2
3

It’s the same output, but really, it isn’t.

If we use PHP’s built in gettype() function, we’ll see that the data types in the above example are actually different.

<?php
$one = 1; 
$two = 2;
$three = "3";

echo gettype($one);
echo gettype($two);
echo gettype($three);
?>

The output for this example would be:

integer
integer
string

The built in PHP function of gettype() doesn’t display what’s held in the actual variable – it displays the type of data held in the variable. It gets the type of a variable.

What if you wanted to complete a calculation by using variables? You can do that. Take a look at this next example:

<?php
$one = 1; 
$two = 2;
$three = 3;

echo $one;
echo $two;
echo $three + $two;
?>

The output of this example would be:

1
2
5

As you can see, the last echo displayed the $three variable and the $two variable being added to each other. To do this, we used one of PHP’s arithmetic operators. More specifically, it was the addition operator.

Floats

In PHP, floats are considered to be floating point numbers. They have other names, such as doubles or real numbers and can be specified with the following syntax:

<?php
$first = 6.674; 
$second = 4.5e7; 
$third = 9E-42;
?>

Basically, floats in PHP are numbers that use decimal points.

Let’s go over an example of some PHP code where we use floating point numbers.

<?php
$distanceOne = 6.9; 
$distanceTwo = 7.2;

echo $distanceOne;
echo $distanceTwo;
echo $distanceOne + $distanceTwo;
?>

Much like the examples used for the integer data type, this example will output the value of the first two variables as well as the sum of the two variables added together. It would look like this:

6.9
7.2
14.1

Can you mix data types, such as integers and floating point numbers? Yes, you can. If we added a third variable of the integer data type and added it to the other two floats, it would return a float as a result.

<?php
$distanceOne = 6.9; 
$distanceTwo = 7.2;
$distanceThree = 10;

echo $distanceOne;
echo $distanceTwo;
echo $distanceOne + $distanceTwo + $distanceThree;
?>

The output for this example would be:

6.9
7.2
24.1

Strings

A string is a collection of characters enclosed in quotes. These quotes can be either single or double. Here’s an example of a string:

<?php
$name = "Jay Gaulard";
?>

or

<?php
$name = 'Jay Gaulard';
?>

Notice how I changed the quotes from double to single. They both work.

If I wanted to create a string variable and then echo its value, it would look like this:

<?php
$greeting = "Hi. My name is Jay.";
echo $greeting;
?>

The output would be:

Hi. My name is Jay.

Let’s say that we want to return just one letter from our greeting variable. The way we would do this is to add curly braces right after the echoed variable and put the location of the zero base indexed letter we would like to return. It would look like this:

<?php
$greeting = "Hi. My name is Jay.";
echo $greeting{0};
?>

And it would return this:

H

Since the index we use is zero based, the location of each letter would be relative to that. The first “H” is at location “0” and the next “i” is at location “1” and so on. Basically, to return a specific letter, all you need to do is put the location of that letter in those curly braces after your variable.

You can also change a specific letter in your greeting variable if you wanted to. Let’s say you want to change the letter of my first name. You want my name to be Zay instead of Jay. In order to accomplish this, you would need to alter your variable.

<?php
$greeting = "Hi. My name is Jay.";
$greeting{16} = "Z";
echo $greeting;
?>

In order to change the letter of my first name, I counted over, starting at 0, to see what position the “J” was in. It was in position number 16. Then, I included the same variable as I had before ($greeting) and said, “I want to change the character in position number 16 to “Z.” The output should be this:

Hi. My name is Zay.

If you’d like to add a second string variable that says something else and would like it to echo on its own line upon returning it, you’d need to add an escape sequence to your first string. In this case, to create a new line, your escape sequence would look like this:

<?php
$greeting = "Hi. My name is Jay.\n";
$secondLine = "I love practicing Jiu-Jitsu.";
echo $greeting;
echo $secondLine;
?>

Do you see how I added the backslash and the “n” at the end of my first string? In this case, the output should look like this:

Hi. My name is Jay.
I love practicing Jiu-Jitsu.

To learn more about PHP escape sequences, take a look at this page.

Booleans

Boolean values are simply true or false. They are used during conditional testing in coding. When questions need to be answered and acted upon, a boolean can become invaluable. Is his hair red? If so, then do something. Does he have a diver’s license? If so, do something. To define something as a boolean true or false, you would use the keyword “true” or “false” when defining your variable. I’ll include some examples of booleans below.

$x = true;
$y = false;

Here’s a good working example from one of my classes at Treehouse:

$bool = TRUE;
var_dump($bool);
$bool = FALSE;

This should output:

bool(true)

Now, what we’re going over here is the order of operations in PHP and then asking for a confirmation to see if what we did is working. First, we set the variable “$bool” to true. Then, we asked PHP if that was working by taking advantage of the “var_dump()” function. Since we ran the var_dump() function directly after the first variable, it returned as true. It hadn’t hit the next variable yet. If we ran the var_dump() function one more time, after the second variable, then we’d get a different output:

$bool = TRUE;
var_dump($bool);
$bool = FALSE;
var_dump($bool);

The output would look like this:

bool(true)
bool(false)

For a more extensive overview of the var_dump() function, check out this page.

It’s important to remember that anything in PHP with a value greater than 0 would be considered true. If the value is 0 or an empty string, it would be considered false. To see some great examples of boolean true and false values, take a look at this page.

If you’d like to test something in PHP to see if you’ve got a true or false value, you can use type casting. I’ll give you an example of what that looks like:

<?php
var_dump((bool) "");
var_dump((bool) 0);
var_dump((bool) 0.0);
var_dump((bool) array());
?>

The output of these four test above would be:

bool(false)
bool(false)
bool(false)
bool(false)

If you updated the values of the tests above to actually have values like this:

<?php
var_dump((bool) "Jay");
var_dump((bool) "14");
var_dump((bool) 0.1);
var_dump((bool) -1);
?>

You would get an output that looked like this:

bool(true)
bool(true)
bool(true)
bool(true)

This is because all the values above are something. They have value – even the negative integer.

Constants

Similar to variables, constants hold values. Unlike variables, constants cannot change their value or become undefined throughout a program. Once set, constants become global across the entire script.

Naming a PHP constant is much like naming a variable or a function – it follows the same rules. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

In order to create a constant in PHP, you need to use the define() function. Within the define() function, reside a few parameters.

name: The name of the constant.
value: The value of the constant.
case-insensitive: Whether the constant name should be case-insensitive. Default is false.

I’ll give you a few examples of constants below:

define("YEAR", 2014);

In the example above, the name of the constant is “YEAR” and the value is “2014.” When naming a constant, it’s common to use all caps. Also, if you notice, the name of the constant doesn’t begin with the dollar sign symbol, like variables do.

Here is an additional example:

define("YEAR", 2014);
define("JOB_TITLE", "Teacher");

In this example, the second constant name is two words and they are connected by an underscore. If we left a space between the two words, the constant would be invalid. Also notice how the value in the second constant is enclosed in quotes. That’s because it’s a string. The YEAR constant’s value was an integer, so it doesn’t need the quotes.

One final word about the above – constants are generally defined at the very top of a page, before any HTML code. I’ll show you how to echo them below.

If we’re interested in displaying the value of a constant on our page, we can simply echo it:

echo YEAR;

Which will display the following:

2014

Arrays

In PHP, arrays are variables that hold multiple values. In order to create an array, you would need to use the array() function. Here’s what an array might look like:

$array_example = array();

If we use the print_r() function to check out some information about our variable, we’ll find an empty array.

print_r($array_example);

Here is our output:

Array
(
)

Like I said, an empty array.

If you’d like to write an array using shorthand, you can do that like this:

$array_example = [];

If I used the print_r() function to look at the array’s information again, I would end up with the same exact information as the previous example gave me.

If you wanted to populate your array, you could do so with any data type. You can use strings and integers and all the rest. I’ll give you a populated array example here:

$car_types = array("Ford", "Chevy", "Dodge");

Notice how I put my data in between the parenthesis and surrounded each string with quotes. You can either use single or double quotes inside your array. Also, I separated each piece of data with a comma.

If we want to see our array’s information again by using the print_r() function, we can do it. We’ll most likely find a different output.

$car_types = array("Ford", "Chevy", "Dodge");
print_r($car_types);

The output would look like this:

Array
(
[0] => Ford
[1] => Chevy
[2] => Dodge
)

What we’re looking at here is very straightforward. For each car type I put into the array, I was returned a value, which is the car type. On the same line as the value, is the key. A key is the position the value resides in the array. Since keys begin at 0, the first value has a 0 key. The second has a key of 1, etc… Together, the keys and values are called key value pairs.

If we want to access and display only one value in our array, we could write code like this:

echo $car_types[0];

Since we’re echoing and we’re only choosing one value – the value in the 0 position of our array, our output will look like this:

Ford

Ford is the value at key number 0.

In order to change a value in your array, you would need to write some code that would identify the array, then identify which value you’d like to change by giving the key and then give the new value in quotes. It looks like this:

$car_types[1] = "Mazda";

In the example above, I just changed the value “Chevy” (which had a key of 1) to “Mazda.”

Like I mentioned above, you can use any data type in an array. Below, I’m going to give an example of an array like that.

$ford_car = array("Silver", 2015, 36.5, TRUE);
print_r($ford_car);

And if we used the print_r() function again, like we did above, this would be our output:

Array
(
[0] => Silver
[1] => 2015
[2] => 36.5
[3] => 1
)

What we have here is the:

Color of Silver (string)
Year of 2015 (integer)
Tire Pressure of 36.5 (float)
Power Door Locks or Not (Boolean)

If you’d like to add an additional value to an array, you would write code like this:

$ford_car[] = "Bucket";
print_r($ford_car);

The empty brackets indicate a new key and a value. This is case, if we call for the array information again, it would look like this:

Array
(
[0] => Silver
[1] => 2015
[2] => 36.5
[3] => 1
[4] => Bucket
)

Associative Arrays

Like arrays, associative arrays are variables that contain multiple values. The difference between the two, though, is that associative arrays are arrays that give you the ability to create your own keys. You may assign these keys as string (or other data type) values and you are able to name them.

I’ll give you an example of an associative array below. If we start off by reviewing our original array, things will look like this (reorganized slightly):

$car_types = array(
    "Ford", 
    "Chevy", 
    "Dodge"
    );
print_r($car_types);

And the output of the print_r() function will look like this (same as a few examples ago):

Array
(
[0] => Ford
[1] => Chevy
[2] => Dodge
)

If we wanted to assign our own key to each on of these values, we can do that. We would have to modify our code though.

$car_types = array(
    "Florida" => "Ford", 
    "Texas" => "Chevy", 
    "Nebraska" => "Dodge"
    );
print_r($car_types);

If you’ll notice above, I added a string (enclosed in quotes) and an equal sign (=) along with a greater than symbol (>) before each of our existing values. The first string in each line will serve as our key and the second string in each line will serve as our value. In the example above, I chose to display the state each car dealer is located as the key and the brand of vehicle they sell as the value.

Now, if we look at the modified output of our print_r() function, it should look like this:

Array
(
[Florida] => Ford
[Texas] => Chevy
[Nebraska] => Dodge
)

Notice how each key has changed.

If you’d like to pull out and display only one value of your associative array, you can write code that looks like this:

echo $car_types["Florida"];

Your output should look like this:

Ford

If you’d like to modify your array, like we did in an earlier example, you can do it this time, like this:

$car_types["Florida"] = "Datsun";

This will update the “Florida” key with a new value. In this case, the new value for the car dealer in Florida is Datsun. The output for the above should look like this:

Datsun

If you’d like to add an entirely new key and value to your array, you can write code that looks like this:

$car_types["Georgia"] = "BMW";

What we did here was to type our array name, followed by the name of the key we’d like to create. Then, we gave that key a value.

If we use the print_r() function to see how our array looks now:

print_r($car_types);

It should look like this:

Array
(
[Florida] => Datsun
[Texas] => Chevy
[Nebraska] => Dodge
[Georgia] => BMW
)

Notice how the value for the Florida key changed to “Datsun” and how the new key and value appeared. Good stuff.

—–

That’s all I’m going to write for now. Up next, working with types and objects in JavaScript.

Filed Under: Development Tagged With: PHP

  • 1
  • 2
  • Next Page »

Connect With Me

  • Facebook
  • Google+
  • Instagram
  • Pinterest
  • RSS
  • Twitter

RECEIVE MY POSTS BY EMAIL!

Interested in receiving my posts by email? This is your chance! Simply place your email address in the box below and I'll deliver each and every post I write directly to your inbox.

Follow Us on Facebook!

IndustryDev

Check Us Out on Instagram!

Load More…Follow on Instagram

Recent Posts

  • Using the Tone Curve in Adobe Camera Raw to Reduce Clipping February 20, 2019
  • How to Set Your Canon Rebel Camera For Continuous Shooting February 18, 2019
  • How to Use the Noise Reduction Feature in Adobe Lightroom February 16, 2019
  • Using the Dust & Scratches Filter to Clean Up a Photograph February 15, 2019
  • Use a Focus Rail For Better Macro Photography February 11, 2019

Most Popular Posts

  • How to Export Video From Adobe Photoshop How to Export Video From Adobe Photoshop
  • How to Set the Photo Quality in your Canon Rebel DSLR Camera How to Set the Photo Quality in your Canon Rebel DSLR Camera
  • How to Speed Up & Slow Down Video in Adobe Photoshop How to Speed Up & Slow Down Video in Adobe Photoshop
  • How To Stop the Flash From Popping Up On Your Canon Rebel DSLR Camera How To Stop the Flash From Popping Up On Your Canon Rebel DSLR Camera
  • How to Adjust the Mouse Click & Scroll Settings in Windows 10 How to Adjust the Mouse Click & Scroll Settings in Windows 10

About IndustryDev

IndustryDev is an online publication that focuses primarily on lovers of the digital world. We write articles that cast a wide net, including those that discuss website development, design and WordPress. We also post, daily, about the image related aspects of the web, including photography and illustration, along with other topics like blogging and SEO.

Read More

RSS IndustryDev Discussion Forum

  • What's the Easiest Way to Fix Over-Exposure & Under-Exposure Clipping? February 21, 2019
  • Tips & True Costs For Selling Greeting Cards on Etsy February 21, 2019
  • How Can I Set My Canon Rebel T3i to Continuous Shooting Mode? February 19, 2019
  • American Goldfinch Bird Photography Nature Greeting Card with Envelope February 19, 2019
  • Can I Get Rid of Grain in My Photos With Adobe Lightroom? February 18, 2019

Tags

Bridge Camera Lenses Camera Raw Camera Settings Channels CSS Dev Tools Graphic Design Hosting HTML Interviews JavaScript Learning Lightroom Macro Photography Masking Night Photography Photoshop Photo Tips PHP Post Processing Selections SEO Shapes Smart Objects Video WordPress

Recent Comments

  • Jay Gaulard on 7 Search Engine Optimization Tips For Small Business: “You are very correct, Mike. I wrote this post a while ago, but it's interesting to follow the trajectory of…” Feb 18, 17:24
  • Mike Khorev on 7 Search Engine Optimization Tips For Small Business: “Onsite SEO is important, but only one piece of the puzzle... It's funny, 10 years ago you would've had…” Feb 18, 16:24
  • Jay Gaulard on How to Reset Edit Settings Back to Default in Adobe Camera Raw: “Hi Charleen, I'm assuming you are talking about the small circle identifier that appears in Adobe Bridge after…” Feb 11, 15:57
  • charleen smith on How to Reset Edit Settings Back to Default in Adobe Camera Raw: “Hi Jay, Your instructions for returning a dng to its original settings were very clear. I…” Feb 11, 15:20
  • Jay Gaulard on How to Export Video From Adobe Photoshop: “Hi Mayur, I've actually had this happen. I just need to remember what was causing it. I'll reply…” Feb 5, 08:13

ARCHIVES

  • 2019: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
  • 2018: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
  • 2017: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
  • 2016: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
  • 2015: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec

Copyright © 2019 · IndustryDev.com Web Design & Photography Blog · About · Write For Us · Contact · Privacy / Terms · Archives