Search

PHP Coding & Development

  • Thread starter WendyMay
  • Start date
WendyMay

WendyMay

Member
Joined
May 11, 2021
Messages
142
Reaction Score
0
Points
21
  • #1

What is PHP?​

Developing for WordPress requires a working knowledge of PHP. WordPress’ core code is written in PHP and PHP is used extensively in themes and plugins. While developing in Genesis, the use of PHP is minimized, but a developer still needs to understand functions, loops and arrays. With this in mind, I decided to brush up on my PHP skills with Treehouse and Lynda.

I wouldn’t normally do this, but I’m going to show you a function that was written in PHP. It’s part of the Genesis Framework. The reason I wouldn’t normally do this is because, when introducing a topic, I like to ease into some sort or a definition and then a history. After that, simple code that eventually gets more complex. On this occasion though, I think it’ll be helpful to take a look at the syntax. I’m not even going to discuss it – I simply wanted to show what PHP code looks like.

Code:
function genesis_do_subnav() {
 
    //* Do nothing if menu not supported
    if ( ! genesis_nav_menu_supported( 'secondary' ) )
        return;
 
    $class = 'menu genesis-nav-menu menu-secondary';
    if ( genesis_superfish_enabled() ) {
        $class .= ' js-superfish';
    }
 
    genesis_nav_menu( array(
        'theme_location' => 'secondary',
        'menu_class'     => $class,
    ) );
 
}

My PHP History​

Back when I first began using PHP, things were quite basic. My initial use was to simplify websites I was creating in HTML by “including” parts of a template (header, footer, navigation). I took advantage of PHP’s “Include Statement.” If I created separate files for the header, footer and navigation and included them, I wouldn’t have to go around and update every single page of the website if I wanted to change something in those areas of the template. It was, and still is, a really great feature.

Obviously, PHP has become much more complex throughout the years. In all honesty, I really don’t even know how to read the code anymore. I could most likely figure it out because of the classes I’ve taken in JavaScript, but as far as writing it, I’m not so sure.

PHP’s History​

I’ll give you a rundown of what PHP was and what it’s become. Very simple. And if you’d like to read the full history of PHP, you can find it here. I just consolidated the interesting parts.

1994 – Rasmus Lerdorf created PHP and called it Personal Home Page/Forms Interpreter (PHP/FI).

1995 – Personal Home Page Tools (PHP Tools) was released publicly with extended basic functionality.

1997 – PHP/FI 2 was released after an organic development team took hold of the PHP project.

1998 – PHP 3 was released with a rewritten parser and was called PHP: Hypertext Preprocessor.

(It’s funny, because I remember the days of naming the extention of a PHP file, .php3.)

2000 – PHP 4, powered by the Zend Engine was released.

2004 – PHP 5 was released, powered by the new Zend Engine II.

2008 – Support for PHP 4 began to wane as the “GoPHP5 initiative” gained traction.

2014 – Work continues on the next version of PHP and it hasn’t been decided if this version will be called PHP 6 or PHP 7.

Obviously, there is a lot more history above and beyond what I just wrote, so, if interested, you can head off and read that on the many resources online. I merely wanted to offer a fast background. Please be aware though, the PHP of today hardly resembles what PHP once was, but it still remains HTML centric. You can embed PHP snippets and code blocks directly into your HTML code.

So, What is PHP?​

PHP, simply put, is a server side scripting language. Unlike JavaScript, where the code is called and processed on the client’s machine (computer), PHP is called from client machine and processed on the server. The results are then returned to the client.

Now, I’m not expert, but in my opinion, this may have some advantages. I’m thinking about processing power here. If someone is running a really hairy bit of code, perhaps it’s better that the server perform those challenging operations as opposed to the client. Who knows what processing power the client has.

How Does PHP Work?​

The actual concept of PHP is fairly simple to understand. The same way your browser interprets HTML, your server (running PHP) interprets PHP.

I’ve written the most popular and basic example below:

Code:
<!DOCTYPE html>
<html>
    <head>
        <title>A Very Simple PHP Example</title>
    </head>
    <body>
        <p>Hello <?php echo 'World'; ?>!</p>
    </body>
</html>

This outputs, “Hello World!” (without the quotes)

Let’s go through the above code for just a moment. Everything you see above is HTML, except for this section:

Code:
<?php echo 'World'; ?>

I’ll explain what’s going on. When you embed PHP code into your HTML document like we did above, your browser knows what to display by itself. It’ll interpret and display the HTML sections. When your browser is confronted by PHP delimiters, it knows it needs to let the server do its thing. The server takes that chunk of code and makes use of the syntax written inside the delimiters. in this case, the syntax is “echo,” two single quotes and a semicolon. The delimiters in use are the most popular for PHP. They are <?php to open and ?> to close PHP.

If I only included the PHP snippet on the page with nothing else, just “World” would be the output, minus the quotes.

Some Simple Rules​

When you want to begin using PHP on a web page, you need to follow a few rules. I’m going to go over them now.

First, in order for the PHP interpreter on the server to know that it’s dealing with PHP, you need to name your files using the “.php” extension. This will give the server the heads up. Second, when you want to insert a PHP code block into your web page, you need to use (like I said above) the opening and closing PHP code block code, which is:

Code:
<?php ...your code right in here... ?>

If you’d like to “echo” or output some simple text from a PHP block onto your web page, you need to use the “echo” function. Note: there is some debate whether or not “echo” is a function or not. You can read about that here.

Here is an example of echo in use:

Code:
<?php echo "Hello World!" ?>

Notice how I used the name “echo” inside the code block and then use some double quotes. I could have just as easily used single quotes, which I did in the other examples. There are some cases, though, where I’d want to take care of which quotes I’d use, but that’s for a later post. I found an excellent tutorial that covers the use of single and double quotes in PHP. You can take a look at that tutorial here. Also, take a look at how I used the semicolon in the first “Hello World” example I gave. I used a semicolon to close the code. Then, in the example just above, I left the semi colon off. Here’s the rule on that:

“As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement. The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block. The closing tag for the block will include the immediately trailing newline if one is present.” (read more)

I hope you enjoyed my short introduction of PHP. If you have questions and comments, please leave them in the comment section below. Thanks!
 
WendyMay

WendyMay

Member
Joined
May 11, 2021
Messages
142
Reaction Score
0
Points
21
  • #2

PHP Variables, Statements, Comments & Whitespace​

I’m going to cover a plethora of topics today, including some basic areas of beginning PHP. I think these are important to understand because, if you’re into this programming language, this is your foundation. Every day you code with PHP, you’ll use each of what I’ve included in the title of this post. You can’t get away from them so it’s critical to embrace the basics and make them your own.

PHP Variables​

What is a PHP Variable?

I’ve been taught this time and time again. I believe the very first occasion was with Simon Allardice over at Lynda, and then during multiple courses, multiple places. In the most basic sense, a variable is a container to store data. The container has been described as a box and the data has been described as what you place in the box. I’ll give you a simple example.

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

In the example above, the container, or variable, is $name and the data is Jay Gaulard. Also, if you remember from my previous PHP post, this variable and piece of data are enclosed inside PHP delimiters. Those delimiters are <?php to open and ?> to close PHP. If you’re interested in learning more about PHP syntax, you can check out a great resource here.

One more short example just to build on the last and pummel this idea home.

Code:
<?php
$name = "Jay Gaulard";
$x = 5;
$y = 10;
?>

As you can see, all I did was to simply add two more variables with their accompanying data. Now, we have the $name variable, as well as an $x variable and a $y variable.

PHP Variable Rules

When writing PHP variables, there are a few rules to follow. They aren’t terribly challenging to grasp or to remember, but they sure are important. If you fail to obey one of these rules, you’re going to have a bit of trouble attempting to get your program to work. You can either read these rules over here, or just read them below. They are the same no matter where you look.

Rules when writing PHP variables:

– A variable starts with the $ sign, followed by the name of the variable.
– A variable name must start with a letter or the underscore character.
– A variable name cannot start with a number.
– A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
– Variable names are case-sensitive ($dog and $DOG are two different variables).

Working With PHP Variables​

I’m going to start working with some PHP variables in this section to give a background on how things look in a real HTML web page. You’ll get a chance to see how fun and powerful PHP variables can be.

Code:
<?php
$name = "Jay Gaulard";
?>
 
<!DOCTYPE html>
<html>
  <head>
    <meta charset=utf-8>
    <title><?php echo $name ?></title>
  </head>
  <body>
      <h1>What's My Name?</h1>
      <p>Hi. My name is <?php echo $name ?>.</p>
  </body>
</html>

In the example above, you can see that we’ve got a real, working (yet simple) HTML page. I’ve written a PHP variable up above the beginning of the HMTL. Since the server will use this PHP variable before any of the HTML is rendered, having the variable there will in no way impact the HTML.

The $name variable is set to Jay Gaulard. If you continue to follow the page down, you’ll see that the title of the web page will be titled, “Jay Gaulard.” That’s simply the output of the $name variable. Also, after the heading in the page that asks, “What’s My Name?,” the output will be, “Hi. My name is Jay Gaulard.”

Now, if we wanted to spice things up a bit, we could easily add a second variable to the code block up at the top of the code. Let’s add a color variable to set my favorite color. Then, we’ll add that color to the sentence on the page.

Code:
<?php
$name = "Jay Gaulard";
$color = "Blue";
?>
 
<!DOCTYPE html>
<html>
  <head>
    <meta charset=utf-8>
    <title><?php echo $name ?></title>
  </head>
  <body>
      <h1>What's My Name and Favorite Color?</h1>
      <p>Hi. My name is <?php echo $name ?> and my favorite color is <?php echo $color ?>.</p>
  </body>
</html>

I think you get the idea. Now, the output of the sentence on the page will be, “Hi. My name is Jay Gaulard and my favorite color is Blue.”

Order of Operations​

Let’s say, for some wild reason, I wanted to change my name that’s displayed on this webpage to my nickname. Some people call me Bob. But let’s also say that, for some reason, I don’t have access to the HTML part of the code. All I’m able to do is to edit the PHP code block up at the top. Well, in order to make my nickname (Bob) appear as my name on the page, all I’d have to do is create another PHP variable called $nickname and set it to Bob. Then, I’d take advantage of the order of operations in PHP.

Code:
<?php
$name = "Jay Gaulard";
$color = "Blue";
$nickname = "Bob";
$name = $nickname;
?>
 
<!DOCTYPE html>
<html>
  <head>
    <meta charset=utf-8>
    <title><?php echo $name ?></title>
  </head>
  <body>
      <h1>What's My Name and Favorite Color?</h1>
      <p>Hi. My name is <?php echo $name ?> and my favorite color is <?php echo $color ?>.</p>
  </body>
</html>

As you can see above, I adjusted the PHP code block at the top of the page. I added the $nickname variable and then set the $name variable to that. The original $name variable was overwritten by the new data. Now, every place $name is called on the page, my nickname will appear and I didn’t have to change any of the code, besides the PHP code block up at the top.

Commenting PHP Code​

There are many reasons why programmers comment code. The one reason I hear most frequently is that coding gets hairy at one point or another so commenting is a way to remember what the heck is going on. Sure, by the time you start writing code, you should have the skills to read it, but many folks prefer to avoid wasting unnecessary time on interpreting what they may have written (sloppily) years ago and simply get to the point. Also, if you’re working on a team, your logic may differ from a team member’s. It sure would be nice if you added a few comments here and there to give them a clue as to what was going through your head at the time of writing. So, what are some good reasons for clearly commenting your code?

Reasons For Using Comments in PHP

– To assist in remembering what you wrote years, months, days ago.
– To assist team members in understanding what you wrote or intended to happen.
– To keep code readable and understandable over multiple files.
– To help the public (who may have purchased a template or otherwise from you) read and understand your code.
– To comment out test code you may be working on.
– To offer a description (at the very top of your code – header comment) of what your code does.
– To explain what large chunks of code are meant to do…and so on.

Types of PHP Comments

In the example below, I’m going to add a comment above each variable, to explain what the variable is. These variables are probably already obvious, but I’m sure you can imagine more challenging areas of code that would call for some slick commenting.

Code:
<?php
// This is my full name
$name = "Jay Gaulard";
 
// This is my favorite color
$color = "Blue";
 
// This is my nickname
$nickname = "Bob";
 
// Overwriting full name with my nickname
$name = $nickname;
?>

So, this type of comment uses two // (forward slashes). Everything on the line after those slashes is considered a comment by the PHP interpreter and is not displayed on the page.

If you wanted to, you can also comment out a line of code. Say you were testing things out and getting creative and you just wanted to see what you happen if that line wasn’t run. You could add two slashes before that line of code.

Code:
<?php
$name = "Jay Gaulard";
$color = "Blue";
$nickname = "Bob";
// $name = $nickname;
?>

In the above example, I commented out the last variable, so any $name variable in my HTML code would revert back to the original full name I used above. The PHP order of operations that I wrote about above would not apply. Everything after the two slashes would be ignored.

If you’d like to write a multi-line comment, you could either write two forward slashes at the beginning of each line (not recommended) or you could use a proper multi-line comment. Here’s what that looks like:

Code:
<?php
 
/*
These variables are meant
to define my name, my
favorite color and my
nickname
*/
 
$name = "Jay Gaulard";
$color = "Blue";
$nickname = "Bob";
$name = $nickname;
?>

So, as you can see, everything in between the forward slash and the asterisk and vice-versa at the end, is ignored. You can even use a multi-line comment to comment out an entire block of code, like this:

Code:
<?php
 
/*
 
$name = "Jay Gaulard";
$color = "Blue";
$nickname = "Bob";
$name = $nickname;
 
*/
 
?>

Now, all my variables will be ignored.

If you enjoy learning about PHP comments, I encourage you to check out the official PHP documentation page on just that.

PHP Statements​

Statements in PHP are lines that end in a semicolon. Take a look at the following example:

Code:
<?php
// This is my full name
$name = "Jay Gaulard";
 
// This is my favorite color
$color = "Blue";
 
// This is my nickname
$nickname = "Bob";
 
// Overwriting full name with my nickname
$name = $nickname;
?>

In the above code, lines 3, 6, 9 and 12 are statements. These are the lines that end in semicolons. Think of statements in PHP as lines or sections of code that are run or executed. They matter and they alter what’s going to happen on a page. If you have a single line of PHP mixed in with some HTML code and there is no semicolon, it’s still considered a statement because it’s a line of code that’s going to run and change what’s happening, or could potentially happen on the page.

Whitespace in PHP​

In general, whitespace that is outside of quotes in PHP is ignored. Here is an example of that:

Code:
<?php
$name = "Jay Gaulard";
$color = "Blue";
$nickname = "Bob";
$name = $nickname;
?>

The code above will be interpreted exactly the same as the code below.

Code:
<?php
 
$name = "Jay Gaulard";
 
$color = "Blue";
 
$nickname = "Bob";
 
$name = $nickname;
 
?>

The spaces in between the variables in the above example will not be interpreted as something that matters. Also, whitespace before and after pieces of a statement are ignore. So if I add a bunch of spaces before and after the equal sign in the first variable, it doesn’t matter.

Code:
<?php
$name      =      "Jay Gaulard";
$color = "Blue";
$nickname = "Bob";
$name = $nickname;
?>

Now, there is an area where whitespace does matter and that’s inside a string. In the above example, strings are “strings” of characters inside the quotes. So, if we add some spaces inside the quotes of the first variable, it will alter the output.

Code:
<?php
$name = " Jay Gaulard ";
$color = "Blue";
$nickname = "Bob";
$name = $nickname;
?>

If we now run the code from our first example:

Code:
<?php
$name = " Jay Gaulard ";
?>
 
<!DOCTYPE html>
<html>
  <head>
    <meta charset=utf-8>
    <title><?php echo $name ?></title>
  </head>
  <body>
      <h1>What's My Name?</h1>
      <p>Hi. My name is <?php echo $name ?>.</p>
  </body>
</html>

It would output looking like this:

“Hi. My name is Jay Gaulard .”

Notice the spaces before and after my name. Whitespace inside strings is taken literally.

Wow, that was a lot of writing. I hope you enjoyed my post on PHP variables, statements, comments and whitespace. I’m learning a tremendous amount over at Treehouse and if you’re interested in this type of thing, I encourage you to get over there to begin your journey. If you do decide to sign up, you might also want to create a blog of your own to do something similar to what you see here. Enjoy!
 
WendyMay

WendyMay

Member
Joined
May 11, 2021
Messages
142
Reaction Score
0
Points
21
  • #3

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.

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

Code:
<?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.

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

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

Code:
<?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.

Code:
<?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.

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

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

or

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

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

Code:
<?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.

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

Code:
<?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.

Code:
$x = true;
$y = false;

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

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

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

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

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

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

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

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

Code:
$array_example = array();

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

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

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

Code:
$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.

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

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

Code:
$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.

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

Code:
$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):

Code:
$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.

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

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

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

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

Code:
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.
 
WendyMay

WendyMay

Member
Joined
May 11, 2021
Messages
142
Reaction Score
0
Points
21
  • #4

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.

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.

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

Code:
<?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.

Code:
<?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.

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

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.

Code:
<?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
 
WendyMay

WendyMay

Member
Joined
May 11, 2021
Messages
142
Reaction Score
0
Points
21
  • #5

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.

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

Code:
<?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.

Code:
<?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.

Code:
<?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 statements 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:

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

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

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

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

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

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:

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

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:

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:

Code:
<?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?
 
WendyMay

WendyMay

Member
Joined
May 11, 2021
Messages
142
Reaction Score
0
Points
21
  • #6

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.

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

Code:
<?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.

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

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:

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

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:

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

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

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

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!
 
WendyMay

WendyMay

Member
Joined
May 11, 2021
Messages
142
Reaction Score
0
Points
21
  • #7

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

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

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

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

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

Code:
<?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.

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

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:

Code:
print_r($total);

We’ll use:

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

Code:
<?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.”

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

Code:
$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.

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

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

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

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

Code:
<?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 below.
 
WendyMay

WendyMay

Member
Joined
May 11, 2021
Messages
142
Reaction Score
0
Points
21
  • #8

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.

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.

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:

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

Code:
<?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.

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.

Code:
<?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.

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

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.

Code:
<?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.
 
Top