PHP Basics

Intro

I needed a refresher course in PHP, so I took the codecourse video series PHP Basics.

This site is the result. In following the series, I've tried to improve on the examples where I can, and wrap it all up in a nice interface.

This site is best understood along with the videos, and alongside the source code on github.

PHP output, that is to say when specific results from the php code depend on variable values etc, are shown like this.

Datatypes


Strings

Korvin

Integers and Floats

Account number: 71722091Balance: £12000

Booleans

This section should be fairly empty, since $sectionBoolean is set to:bool(false)
Set it to true and this section will expand

Arrays

Let us echo and var_dump our array $names[], currently empty: Array
array(2) { [0]=> string(5) "David" [1]=> string(4) "Mary" }
echo $names[1] returns: Mary

We have a multi-dimensional array

array(2) {
  [0]=>
  array(3) {
    ["username"]=>
    string(4) "Korv"
    ["email"]=>
    string(13) "km@korvin.org"
    ["likes"]=>
    array(2) {
      [0]=>
      string(7) "history"
      [1]=>
      string(4) "food"
    }
  }
  [1]=>
  array(3) {
    ["username"]=>
    string(4) "Mary"
    ["email"]=>
    string(16) "mary@hotmail.com"
    ["likes"]=>
    array(2) {
      [0]=>
      string(5) "books"
      [1]=>
      string(4) "cats"
    }
  }
}

Let's see if we can access the second user's email.
mary@hotmail.com

Now let's use a foreach loop over the $users array.
Korv Mary
We could use the same technique to output the list of email addresses:
km@korvin.org mary@hotmail.com
and likes?
history,food books,cats

Now lets add a new user and modify a record.
Users: Korv Mary Jeremy
Likes: history,food books,PHP reading,cooking

Null

Null represents a variable with no value; the variable has either been set to NULL, has been unset, or has never been set in the first place. Earlier we set $noName to null. Let's var_dump($noName): NULL

Now let's set and echo the variable: Name

Now let's unset and var_dump the variable: NULL

Now let's set the variable back to NULL, since that's best practice: NULL

Concatenation and Variable Parsing

The current weather is rainy and it's 30.6 degrees
The current weather is rainy and it's 30.6 degrees.
The current weather is rainy and it's 30.6°

Ifs and Ops

If statements - days of the week

In the codecourse video, an integer is set, and an if..if else statement run on the integer as a condition.
We can grab the same integer from the php function getdate(), which returns an array of data about the current date. Running an identical if..if else statement outputs: No day exists beyond Thor's Day!
In this case, the only advantage the if statement confers is the ability to echo a different message for each day. If we just want to output the name of the day, with getdate() we can do it in 2 lines of code. Saturday

As the video explains, if we do need condition checking, it's more efficient to use inbuilt array functions. We can illustrate the difference clearly in our code if we aim to output some more abstract information, such as a god associated with the day.

Today's deity: saturn

To nest or not to nest

If we want to output a string, and then ouput something if the string exceeds a defined length, we can do it with nested if statements:
Success! A name exists! It is Korvin.
If at all possible however, avoid nesting if statements. The same effect can be achieved more readably with an inversion operator:
A name exists! It is Korvin.

Logical Operators

Be mindful of what variables actually return when checking them for truthiness and falsiness. Certain values will always return true or false. The following table illustrates:

Value

Returns

true true
false false
0 false
Positive or negative number true

And

Or

You have the weekend off! Actually though, you don't, since this code is buggy.

Comparison Operators

In the previous example, we set $workingWeekend$ to 1, then used !$workingWeekend as a condition. This works because we're not strictly typechecking. Even the == operator would work. The following examples demonstrate a bug that can arise from non-strict checking, and then fixes this with strict typechecking, using the === operator
Seems legit, but the value was-5
The variable is a boolean and true

Strict typechecking also avoids bugs arising from php automatic typecasting, whereby, for example, strings beginning with an arabic integer number will be cast to integers, thus evaluating as true when checked in non-strict mode.
The $shipsDocked variable is: 1hundred and There is one ship docked
More correctly:
There are 1hundred ships docked

Running checks with the NOT operator using strict typechecking There are 1hundred ships docked

Greater than, less than and equals operators can be used
Not enough rooms available to meet your request.
Not enough rooms available to meet your request.

If we want to keep a room empty regardless of bookings, we could use the equals operator:
Not enough rooms available to meet your request.

Finally, we can combine comparison and logical operators: Rooms available to meet your request.

Switch statements

Used when if statements would be messy. Value: 2

Weather Mood

Arithmetic

Calculating percentages

This section covers addition, multiplication and division, using the + - and * operators.
Total lessons in course: 35 You have now completed 18.2 lessons. That's 52.0% of the course.

Subtraction

Uses the - operator.
Current balance: 12000 Item cost: 250.65 Your balance after purchase will be: 11749.35

Increments and decrements

$completedLessons++ increments the variable by one, and $completedLessons-- decrements: You have now completed 19.2 lessons.And if we decrement by 1: You have now completed 18.2 lessons.

Working with larger numbers

Addition and subtraction can be achieved cleanly and quickly with the =+ and =- operators.
0 points 10 points 8 points

The modulus operator % returns the remainder, and can be used to determine odd and even numbers:
Odd Even Odd Even Odd Even Odd Even Odd Even

The exponent operator raises to a specific power. Assign $a to: 10 Raise to the power of 2: 100 Raise to the power of 9: 1000000000

Loops

Structure of a FOR loop

For loops iterate according to initiator, condition and increment. Given two variables - $totalItems and$itemsPerPage, we can use the for loop to output the number of pages needed.
25 items per page / 66 items.So we need 3 pages. Voila: 1 2 3

We can also use a for loop to loop through an array; although a foreach loop is preferable, this can have some use-cases
David Mary

WHILE and DO...WHILE loops

We can iterate over an incremented variable using a while loop 1 2 3 4 5 6 7 8 9 10

But a more practical use would be a dice game
Target: 3

You rolled the target: 3

Be careful. The following would cause an infinite loop:

  while (true){
    //do something forever
  }
Always ensure the condition will evaluate to false at some point.

do..while loops will run at least once, before condition checking occurs

FOR...EACH loops

There's an example of this in the Datatypes section. It's expanded below to make use of the index values to give us an ordered list.
0: km@korvin.org
1: mary@hotmail.com
2: jem@jem.org

Now let's use a similar technique to loop through a complex array that's 3 levels deep

Topics

PHP Basics

Practice the language

Use PHP on a practical project

Practice the language

How to use a foreach loop

Just do it

Breaking and continuing

Sometimes a loops needs to be broken out of, or skipped. We can easily do this using two keywords: break and continue. The following examples use break for speed, to stop the loop once the desired result has been found, and continue to skip a particular member of the same array.
array(3) { ["username"]=> string(6) "Jeremy" ["email"]=> string(11) "jem@jem.org" ["likes"]=> array(2) { [0]=> string(7) "reading" [1]=> string(7) "cooking" } }
Korv
Jeremy
Xen

Using nested foreach loops, we can find the first user who likes philosophers to be: Xen

Functions

Function to return a name, with optional second name and seperator

echo fullName('Korvin', 'M', ' '); returns Korvin M
echo fullName('Korvin', 'M', '_'); returns Korvin_M
echo fullName(' '); returns NULL

Type hinting, and built in functions func_get_args and array_sum

If we want to ensure our function only accepts a particular datatype, we can hint in the argument: We can use it like this:

$numbers = [4,11,21];
echo add ($numbers);
Returns: 36
or pass the array in directly: echo add ([4,11,21]); 36

func_get_args and array_sum allow us to sum multiple numbers with a function:
So the functions addToo() and sum() both perform this task, the latter without the neeed for a loop:
addToo(4,11,21) returns: 36 sum(4,11,21) returns: 36