When it comes to variables, each programming language has it’s own set of variable types, and programming languages generally fall into one of two camps with variables:

  1. strongly typed, where you have to declare what type of variable something is (and generally, once you declare it, you can’t change the type); and
  2. weakly typed, where you don’t have to specify what type of thing something is (and you can switch the type of thing it is along the way).

PHP has been, and still is, weakly (or loosely) typed. But in the past couple years, with version 7, has begun to offer an option to strongly type things. So, while the great majority of PHP you find “in the wild” follows weak type patterns, you will see more and more strongly typed PHP as things go on. We'll look at things both ways.

Variables themselves in PHP come in 8 main types.
4 of those types are basic types:

  1. integers
  2. floats (numbers with decimals)
  3. strings (a series of characters, strung together), and
  4. boolians (true/false)

4 more are compound (or complex) types:

  1. arrays (data tables or maps)
  2. callables (functions)
  3. objects
  4. resources (usually an external file or input data stream)

(The manual also lists iterables and NULLs as types, but let’s just say for now that iterables are basically arrays and objects that share the certain abilities for moving through and processing the data they contain, and NULLs are any variable that has no set value.)

The Basic Types

The 4 basic types are easy enough to understand. In PHP you don’t need any keyword to define a new variable. For basic variables, the syntax is simply to name it starting with a $ followed by a letter or _ followed by any combination of letters, numbers and underscores you like. So:

An integer:

$number = 25;

A float:

$_float = 3.1416;

A string:

$im_a_string = "I'm a string.";

A boolian:

$I_am_true = false;

Notice, each statement ends with a ;.

Also, notice that for strings, you can use either single or double quotes to indicate the beginning and end of the definition. In most instances, we prefer single quotes, but double quotes come in handy in order to use special characters (like we used the single quote, above) without needing to escape them, or to insert a variable into a string. So we could also have written the above as:

$im_a_string = 'I\'m a string';

Using the backslash as the escape indicator for the special character immediately following. (So, to actually print a backshash character in single quoted strings, you would use \\.)

We can also use the double qoutes to insert a string variable into another string:

$your_name = 'Seth';
$say_hello = "Howdy there, {$your_name}! How ya doin?";
echo $say_hello;

will print to the screen: “Howdy there, Seth! How ya doin?”. In the above, the curly brackets are optional, but recommended since they make make where the variable name ends less ambiguous, both to the human eye and the PHP interpreter. (And now you know that echo is the PHP command for “print the following to the screen”.)

The Compound Types

Are more interesting and powerful. They each have their own syntax as well.

Arrays

You can define an array in either of 2 ways:

The “traditional” syntax, because it goes back to PHP’s beginnings, is:

$foods = array ('apple', 'banana', 'cookie');

The modern syntax is:

$foods = ['apple', 'banana', 'cookie'];

Arrays can be either indexed, like the above examples, or associative, which means each item in the array is a key/value pair. So, here’s an associative array:

$foods = [
    'red-fruit' => 'apple',
    'yellow-fruit' => 'banana',
    'dessert' => 'cookie'
];

(Indexed arrays are actually associative arrays with hidden numeric keys. So if you were to print out the indexed array examples above, you would get:

[
    0 => 'apple',
    1 => 'banana',
    2 => 'cookie
]

Notice also that indexed arrays start with 0.)

In any case, to get at the information stored in an array, you can refer to it by it’s key (or index number).

If I want to see what the value of the red fruit is, I use:

echo $foods['red-fruit'];

and it would give me “apple”.

Or, for the indexed array, I can say:

echo $foods[2];

and it would give me “cookie”.

The real power of arrays is when you need to work with with all the data that’s stored in them as a set. You can loop through them and work with each of the items in sequence.

foreach ($foods as $description => $food) {
    echo "{$food} is a {$description}.";
}

takes each of the items in $foods assigning the key to a new variable $description and the value to a new variable $food, then inserting those new string variables into a string (yet another new variable, but one we never give a name to), which is printed to the screen.

We could name that new string variable instead of printing it, and then we could use that variable to do something else.

foreach ($foods as $description => $food) {
    $sentence = "{$food} is a {$description}.";
    if (strpos(false !== $sentence, 'red') {
        echo $sentence;
    }
}

will print the sentence to the screen only if it contains the word “red”. (Assignment: look in the PHP Manual for how I did that with the strpos() function.)

Callables

As we’ve said, these are functions.

Functions are defined using the following syntax:

function name_that_function($parameter1, $parameter2, $etc)
{
    // code that does stuff goes in here.
}

The above is for weak typing. Notice how none of the parameter variables indicates what kind of variables they are. There is also no expectation defined ahead of time about what, if anything, the function will return after it does its job. But we can define those (and in my opinion, when working with PHP 7, we should).

function name_that_function(string $param1, int $param2): string
{
    // code that does stuff goes in here.
    return 'This is a string.';
}

Now we know what kind of variables need to be passed into the function when it is called (a string and then an integer), and what we should expect to come back when the function is finished (a string). This also necessitates the function to have a return statement that sends the appropriate kind of thing back to wherever it was called from. If we don’t expect anything to come back – the function just does something and exits – we can declare that it is void:

function name_that_function(): void {
    // do stuff
}

takes no parameters and gives us nothing in return.

To call a function, you simply use it’s signature:

echo name_that_function('this is a string', 4);

Objects and Resources

Let’s leave these to a future lesson. We’ll get into resources when we start working with manipulating data contained in external files. And objects are perhaps the most powerful of all the things, but we’ll need to get some practice with functions first.

Assignment

Create a new php file in your php root directory, call it initials.php.

Write a function that takes a single string of the form “Firstname LastName” and returns a new string that is the first and last initials. Then call the function with an appropriate string to print the initials on the screen when you load http://localhost/initials.php into your browser address bar.

To get you started, your file will look something like this:

<?php
function getMyInitials(string $name): string
{
    // You figure this out. Look through the string functions in  
    // the PHP manual, linked above.  
    // Also, it might come in handy to know you can concatinate  
    // (join) strings using the . as in $a_string . $b_string   
}

echo getMyInitials('Caspar Green');