Next, We Do Logicals

What is PHP Structure and How do I use it when coding in PHP?

PHP & PHP Structure

Next we hop into PHP structures - fi else, switches, loops, strings, functions and more. We will cover those along with others like sessions, cookies, file(), exceptions, error handling, regular expressions i.e. RegEx. This can take time, you as the learner have all the time in the world to master PHP structures... take the time now to learn the basic structure elements in PHP, fail fast! There are other structure types per say, however, we cover those noted above. We will include more examples over in the reference portion of the site. Head over there for more information for those non-noob skills!

PHP Control Structures - If Else & Switches

In the control section we cover two variations or categories of executable code. Both sequential and decision, execute code based on conditions. Sequential executes all the code in order, in order the code has been written. Conversely, decision code, will execute once a 'decision' has been made by the user, the code to be executed will follow the users choice in the decision process.

Example in text form, its raining, when raing, a user should put on a rain jacket, rain boots and carry a umbrella in the event it rains more than a drizzle. Output, user puts on rain jacket, rain boots and carries an umbrella. Next example, or the decision example for user in this scenario, if raining, should I put a rain jacket on? Yes or no?. Output, user is asked if they would like to put on on a jacket if it is raining.

Ok, so the php version.... if, then or else. This uses logical operation, if a condition is meet (Boolean true) do something, return true. Otherwise (Boolean false), the constant condition has been meet do something else. This is the true or false scenario. We can include if, else if and else for additional condition or control which might have more than 2 scenarios.

Example 1 - PHP If, If Else, If Else If Else:

Ideally, this is a true or false condition... If some condition is meet or true, execute the following block of code as true. Otherwise the condition is false, execute this block of code.

If, Else
$x = '1';
if ($x == "1") {
echo "hello y'all, looks like you\'ve been here before";
} else {
echo "hello y'all, we see this is your first time here!";

Output: hello y'all, looks like you\'ve been here before

If, Else if, else

Similar to the if, else statement above, we add in other conditions... using the rain scenario, let's include snow... So, if it is rain, do this rain stuff, else if it is snow, do this stuff - wear snow boots, gloves, coat and hat. Else, all conditions above are false, it's a warm day, wear shorts, t and bring a hoodie just incase...

//x equals 2
$x = '2';
if ($x == "1") {
echo "hello y'all, looks like you\'ve been here before";
} else if ($x == "2") {
"hello y'all, we thank you for stopping by, come back anytime";
} else {
echo "hello y'all, we see this is your first time here!";

Output: hello y'all, we thank you for stopping by, come back anytime
Switch/Switch Case

Similar to the if, else, we have the switch case. Switch case will execute the same block of code and depending on the condition, when true, the code will kick out at 'case value' and execute the block of code when said condition is meet. If none of the conditions are meet, the default code is produced or execute as 'no condition' was met in the block of code. So, when using our rain analogy, it might look something like this: When it is sunny, you don't need all those extra items to accompany your outfit... however, if it is snowing, wear a coat, hat, gloves etc. if it is raining, wear a rain jacket, some welly's and pop open your umbrella. If it's a normal day, carry a hoodie incase you get cold!

//Snow Day, show case for a snowy day
$x = "snow day";
switch($x) {
case "warm day":
echo "I'm in my shorts, a t-shirt and some sandles... beach time!";

case "rainy day":
echo "Grabbed my Wellies, a poncho and an umbrella, heard it was raining cats and dogs out here...";

case "windy day":
echo "Oh boy! It's near cyclone weather outside, I'm staying inside today.";

case "snow day";
echo "Oh it's warm, I've got my gloves, some moon boots, warm gloves and a comfy jacket. Nothing is going to stop me today, I'm making that snow man right now!";

Output: Oh it's warm, I've got my gloves, some moon boots, warm gloves and a comfy jacket. Nothing is going to stop me today, I'm making that snow man right now!

PHP Loops, "I say, Loop this!"

Moving on from If, Else, If, Else If, Else and Switch Cases we touch on the loop structure. This might be iterative conditions or conditionals. We will iterate through the code until a condiion is true or met. Loops is one of our favorite ways to iterate through a bunch of conditions to find and execute a piece of code. Plus this concept of iterative coding structure is used a lot of different places, and you can see how helpful it can be once we get into it. Shall We?

For Loop

Starting with the 'for' loop, the code will loop through a block of code, as long as the condition is met. So, this would be similar to may be wearing a pair of gloves as long as the tempurature is below 32° degrees F. Regardless of the tempurature -1°, 30°, 18°, as long as the tempurature is below the 32° degree F mark the condition is true. Also, we will work in an iterative manner.

Our 'For Loop' will start from an 'initial value' for testing purpose 24° degrees as the tempurature we start with will be less than 32° degrees F. We will iterate from 24° - 32° until the condition no longer applies... If the condition, in this case the tempurature raises above 32° degrees, the for loop is no longer valid, the condition is false and kicks out of the loop. We will print the value from the intial tempurature of 24° degrees F, the increments from 24° degrees F to 32° degrees F and stop essentially at 32° degrees F as the conditional for loop no longer meets the condition.

//For Loop
$x = " - freezing"; for ($i = 24; $i < 32; $i++){ echo "Current tempurature $i° degrees $x"; } ?>
Output: Current Tempurature 24° degrees - freezingCurrent Tempurature 25° degrees - freezingCurrent Tempurature 26° degrees - freezingCurrent Tempurature 27° degrees - freezingCurrent Tempurature 28° degrees - freezingCurrent Tempurature 29° degrees - freezingCurrent Tempurature 30° degrees - freezingCurrent Tempurature 31° degrees - freezing

So, in conclusion with the For Loop, we iterate through our hypothetical scenario where a user would like to see tempuratures below 32° and categorizing those as freezing tempuratures. Again, starting at 24° and incrementiing to 32° which has a value of 8 degrees which met the freezing tempurature criteria.

For Each

Quickly, while the For Loop is fresh in your minds eye, let's try a 'For Each' loop or foreach. We will again iterate through values, but this time we will iterate through an array! Hooray! Another array example. Let's start with a list of cars, we used back in the arrays section. More specifically European Wagons!.

//Text variable, for each example. First time we use the '.' to add html after an echo call to print a variable

$y = "Which Wagon is your favorite?";
echo $y;
$cars_list = array("V70","A4 AllRoad","E350","TSX Wagon","Panamara");

foreach($cars_list as $array_values){

echo $array_values . "



Output: Which Wagon is your favorite?
A4 AllRoad
TSX Wagon

And another for loop, looping through an array within or associated with the parent array with access keys. That example might look something like this...

Output: Give me the values associated with the Off Road SUV listing
Volvo is XC90
Jeep is Wrangler Safari
AMG is Hummer

While Loop

Next we have the 'while' loop which executes a block of code until a condition is true, or condition is met. Unlike the for loop where the condition is true and the obverse takes place, output being the false condition. We use a false condition until it is true. This migh tbe helpful when building and maintain data which might rely heavily on a database connection. A likely scenario might be to look up a name and address associated wtih the local town.

Be aware of the spacing and line breaks, ultimately, PHP is forgiving, but syntax still matters here.

Let's loop through names that end in Smith...


echo "Currently, there are [ ";

$i = 0;

while ($i < 5){

echo $i + 1 ." ";



echo "] Smith's who live in the West Chester County, PA Area";


Output: Currently, there are [ 1 2 3 4 5 ] Smith's who live in the West Chester County, PA Area
Do While Loop

As an additional step, 'do while' loops until a value is met, or perform the condition of upto a value or in the following example 11

//Value will be 11

$i = 11;


echo " is $i"." <br>";

while($i < 11);


Output: is 11

A little wrap up on loops, structure etc. We went over 'for' 'foreach' 'while' 'do while' loops, awesome stuff... We are moving forward but if you need time to review. Take the time now, so you have a step up on the subsequential exercises.

PHP Control Structures - Strings

First we have if's, Loops and now strings? What gives? Well, strings... strings are one of PHP's data types and contain alphanumeric characters. Well, we can create strings as well while using stings in language form and 'print' those characters to the web.

You may have notices ' " used in previous examples, when an echo call is made to print what is contained within those quotes or double quotes. More specifcally, we use ' single quotes to indicate what will be contained in the code once executed.

//Don't forget, use the '\' to escape special characters
var_dump('Let\'s look at the following var dump, have the system process the dump to the page and share the number of characters within the string');

Output: string(135) "Let's look at the following var dump, have the system process the dump to the page and share the number of characters within the string"

Helpful when building sites, and need to print something to a webpage etc. We've built this site using echo & '', same for the individual php sections, subsections where text makes sense.

Jake 'The Snake' Roberts, is/was the best wrestler of all time... all time. Period

Here's a curve ball, specifically heredoc. Or we concate strings with double quotes "" on multiple lines etc.

$car_name = "Jeep";
$car_model = "Wrangler";

echo <<< EOT

When I was younger, there was a $car_name Club,

favorite was a lifted Blue '05 $car_model Nitto Tires


Output: When I was younger I was in a Jeep Club, Favorite was a lifted Blue '05 Wrangler Nitto Tires.

And another, Nowdoc strings create something similar to the 'heredoc'... Key here is the quotes, 'Nowdoc' uses the single quotes.

So the Nowdoc example might be something like this:

$car_name = "Toyota";
$car_model = "FJ";

$another_var = <<<'EOT'

When I was young $car_name Club member,

I had a lifted Black '87 $car_model Nitto Tires.


echo $another_var;


Output: When I was young $car_name Club member, I had a lifted Black '87 $car_model Nitto Tires.

PHP String Functions

We will cover the PHP String Functions more indeepth on subsequent pages, but for now here is a quick look at those functions. Althought the following list includes all functions, a full list of string specific functions can be found here - PHP Functions Docs<. Click the link, do some research, try some of the functions locally... come back when you're ready to move on.


Explode - Convert strings into array variables

Array ( [0] => host=localhost:8888 [1] => db=credentials [2] => uid=root [3] => pwd=pa$$word )

lcfirst - Make/Modify first character of a string lower case


md5 - String function used to calculate the md5 hash of a string value


strlen - find out the total number of characters within a string


Need to find and locate a specific character? Try strpos


Need to replace a word within a string, str_replace is that function

this typewritter is old, well worn in by my calculations. I had my first Selectric typewriter in college back in '79

Can't imagine what 'strtolower' would do? how about converting all characters to lower case? Do it with strtolower

ibm100 selectric typewriter

Conversly, how about converting all characters to upper case? Do it with strtoupper




sha1 - String funtion used to calculate the sha-1 hash of a string value


substr - Use this function to return parts of a string value. More importantly, parameters are used to define what will be returned. So, we use 3 parameters and they are: name of variable or string value to be Shortened, Starting Point or position, where the system will start the return value and number of characters (string_length) to be returned.

This a bunch of foobar

substr - Use this function to return parts of a string value. More importantly, parameters are used to define what will be returned. So, we use 3 parameters and they are: name of variable or string value to be Shortened, Starting Point or position, where the system will start the return value and number of characters (string_length) to be returned.

This a bunch of foobar

ucfirst - Make/Modify first character of a string upper case

Right on, right on

PHP Control Structures - Functions

Moving on from Strings, we will tackle functions here.. what a function might look like, how a function is built, same for those functions that are 'native' or global functions built-in to the scripting language.

Although we will not go over the 600 to 700 plus functions within the PHP universe, we do cover the string type, along with numerical, date and user defined.

Right so, what is a function? Ideally it's a block or blocks of code which perform tasks. Hey, the best part of PHP. Functions are scalable, resuseable and easy to integrate/maintain. We like that. Some code that is easy to scale, sustain and reuse... PHP it is.

Covering built-ins, these are functions that are on a global scale, built-into PHP. These are defined functions within PHP to perform tasks.

We covered string functions above, same with the extended list of PHP String Functions... let's cover the others below:


cos - Like sine below, we use cosine for functions of an angle. More specifcally, cosine is equa to the adjacent over hypotenuse. Give sine a try as well.


is_number - ok, need a boolean, and have numeric values to compare? Try is_number, compare two values if argument is true if the value is numeric and false if 'not' a numerica value.

false, not a number and true, it has a numeric value

number_format - Need some visual values, like on a spreadsheet, how can we convert a random numeric value into hundred, thousands etc. with decimal points? Try number_format

Our dream home cost nearly $361,000, today's equivalent to nearly $600K. Crazy, I know, right? Home prices continue to escalate... we all know it's got to come back down at somepoint!

pi - Need some pi? Pi this.


rand - How about a random value? Great for contests!


round - Round to the nearest whole number...


sin - How about he sine of a curve? Or Sine equals opposite over hypotenuse, bet you didn't see that one as a built-in function!


sqrt - Need some squareroot? Function will return the squareroot of a numeric value


tan - Function will return the tangent of the numeric value

Date Functions

Dates work off of the Unix date/time stamp... Unleash your knowledge, have a look over the Unix/Linux links to learn more about those OS/Operating Systems. Very cool stuff.

User Defined Functions

We also call user defined functions as local or local to the script you might be working on. Although user defined functions can be global, these functions help perform specific tasks.

Starting a function? Let's start with a letter or underscore, no numbers allowed. Same with a unique name, lower case without spaces. Although a unique name is required, parameters and return values can be added to strengthen the code and the functional purpose of the script(s).

So, let's create some functions... let's start by adding some foo-bar or in programming language, placeholder text, like Lorem Ipsum but better. You may want to use Lorem in the future, make note of it now...

This is the jumping off point per say, it's all down hill from here; may be up hill sounds better. It's all up hill from here, have at it!

Output: 30
Output: Hello, Mickey Mantle aka "The Mick or Commerce Comet"
Output: 124
Output: So, there are 150ft. swam in 50m. race.

PHP Control Session(S) & Cookies... me like cookies

COOKIES COOKIES COOKIES, gotta love cookies. Anyhow, let's cover cookies for the purposes of the web. A cookie in short is a file, no bigger than 4kb, where the web server information is stored on the client-side machine.

Easy right? Small cookie, 4kb stored on the clients machine... once set, all page requests will follow that cookie trail in both name and value. This 'cookie' is read from the domain in which it was issued. So, for the purposes of this domain - mbemo.com, the parent domain will be read by your client side computer. Unfortunately or not, cookies are all over the place... most of the cookies you'll run into are third-party, set by some other service.

Interestingly enough, the user who creates cookies, will see the value set by the cookie. While you as a separete entity may not view the user created cookie above, you can disable them...

Process => User Does something on the internet, keys in a website and hits go. A cookie is set once the user hits the destination of choice. =>Server sets the cookie on the users machine, upon achieving the destination. There is your connection for future usage.

Need help with other front-end code, jQuery, Bootstrap, JS? We are diligently working behind the scenes to bring our learning platform to the masses. Scripting and/or Object-Oriented languages and more! Check out the main topics contained in this website.