Learning PHP 101 – Built In Functions

PHP tutorials

Functions are reusable bits of code that you use throughout a project. They help to better organize your application as well as eliminate the need to copy/paste repetitive pieces of code. In an ideal world an application should not have multiple functions doing the same thing.

PHP has a lot! of built in functions and while you are not expected to learn all of them at once there are some useful functions that can help in everyday programming and we will start from there.

String Manipulation Functions

Some of the most useful PHP functions are string manipulation functions. As the name suggests they manipulate strings.

Finding the length of a String

The strlen() functions works by passing a string or variable and then returns the total number of characters including spaces.

<?php
    $name = "Matthew ";
    echo strlen($name); // 8
?>

Return part of a String

The substr() function is used to return a substring or part of a string. This function has 3 parameters which you can pass along.

Syntax

substr($string, $start,$length);
  • $string – a string of text or a variable containing a string of text. Input must be at least one character.
  • $start – think of the string as an array starting from [0]. If you wanted to start from the first character you would enter 0. A negative value will go to the end of the string.
  • $length – (Optional) is the number of characters returned after the start character. If this value is less than or equal to the start value then it will return false.
<?php
    $name = "Matthew ";
    echo substr($name, 0, 5); // Matth
    echo substr($name, 2); // tthew
    echo substr($name, -6, 5); // tthew
?>
Note: If you don’t provide a $length parameter, this function will just return the remainder of the string starting from the $start parameter.

Converting strings to UPPER or lower case

Two useful string functions that are simple to use are strtoupper() and strtolower(), these functions can convert your strings to all UPPERCASE or all lowercase.

They are very useful for case sensitive operations where you may require all characters to be lowercase for example.

<?php
    $name = "Matthew ";
    echo strtoupper($name); // MATTHEW
    echo strtolower($name); // matthew
?>

Searching for a needle in a haystack!

Sometimes we need to find a substring within a string and to do that we can use strpos.

Syntax

strpos ($haystack,$needle,$offset)
  • $haystack – this is the string in which you are going to find the $needle starting from [0].
  • $needle – this is what you are going to search for in the $haystack.
  • $offset – (Optional) search will start from this number of characters counted from the beginning of the string. Cannot be negative.
<?php
    $name = "Matthew ";
    echo strpos($name, "M"); // 0
    echo strpos($name, "hew"); // 4
    echo strpos($name, "m"); // false
?>

Notice that the last example is false. That is because this function is case sensitive and could not find a match.

we can almost make use of an if statement and some variables to make the strpos function more useful and meaningful.

<?php
    $string = "I am learning how to use PHP string functions!";
    $search = "JavaScript";
    if(strpos($string, $search) === false) {
        echo "Sorry we could not find '$search' in '$string'.";
    }
?>

This would echo “Sorry we could not find ‘JavaScript’ in ‘I am learning how to use PHP string functions!’“.

Arithmetic Manipulation Functions

As well as string manipulation function, PHP also has functions to manipulate numbers.

Rounding numbers

One of the most commonly used math function is round(). This function rounds numbers with decimal points up or down. You can round a number to an integer (whole number) or to a floating point (decimal numbers).

Syntax

round($val, $precision, $mode)
  • $val – is the value to be rounded.
  • $precision – (optional) number of decimal places to round to.
  • $mode – the type of rounding that occurs and can be one of the following – for more details and examples of modes see PHP docs.
<?php
    $number = 3.55776232;
    echo
        round($number) . "<br/>".    // 4
        round($number, 1) . "<br/>". // 3.6
        round($number, 3) . "<br/>"; // 3.558
?>

Other math functions for rounding are ceil() and floor() . If you simply need to round a number to the nearest whole number then these functions are better suited to that purpose.

  • ceil() – rounds fractions up.
  • floor() – rounds fractions down.
<?php
    $number = 3.55776232;
    echo
        ceil($number) . "<br/>".  // 4
        floor($number) . "<br/>"; // 3
?>

Both functions require a value and unlike round(), do not have any additional parameters.

Generating Random Numbers

Another very common math function is rand() which returns a random number between two numbers.

Syntax

rand($min, $max)
  • $min – (optional) sets the lowest value to be returned. Default is 0
  • $max – (optional) sets the maximum value to be returned. Default returns getrandmax().
Note: getrandmax() on some windows machines will return 32767. You will need to specify a $max value in order to return a larger number.
<?php
    echo rand(). "n"; //10884
    echo rand(). "n"; // 621
    echo rand(2, 10);   //2
?>
Note: End-of-line terminator (n) is used in Unix and Unix-like systems (most servers) to move the carriage down to a new line. Simply put, it creates a new line in source code.

Array Functions

Array or array() is itself a function that stores multiple values in to a single variable. Aside from the array() function there are a number of other functions to manipulate arrays, here we will look at some of the most common ones.

Adding New Elements

Adding new elements to the end of an array can be achieved by calling the array_push() function.

Syntax

array_push($array, $value1, $value2)
  • $array – the array in which you are adding new elements to.
  • $value1 – (required) is the first value to push onto the end of the $array.
  • $value2 – (optional) is the second value to push onto the end of the $array.

You can push as many values as you need.

<?php
    $games = array();
    $array = array_push($games, "Farcry 4");
    $array = array_push($games, "Fallout 4");
    $array = array_push($games, "Metal Gear");
    $array = array_push($games, "Witcher 3");
    echo $array; // returns 4
    var_dump($games);
?>

However is is better to list each element in a single call like this:

<?php
    $games = array(); // target array
    $array = array_push($games, 
        "Farcry 4", 
        "Fallout 4", 
        "Metal Gear", 
        "Witcher 3");
    echo $array; // returns 4
    var_dump($games);
?>

Both methods result in the same outcome. If you echo or print array_push() it will return the number of items to be pushed in to the array.

If you var_dump() the target array you you will see something like this.

array(4) {
  [0] =>
  string(8) "Farcry 4"
  [1] =>
  string(9) "Fallout 4"
  [2] =>
  string(10) "Metal Gear"
  [3] =>
  string(9) "Witcher 3"
}

Sorting an Array

As well as adding items to an array we sometimes need to be able to sort them. PHP has a handy function called “funnily enough” sort() to do just that.

Syntax

sort($array, $sort_flags)
  • $array – the array in which you wish to sort.
  • $sort_flags – (optional) modifies the sorting behavior. For more information see PHP docs.

By default the sorting behavior will reorganize an array alphabetically or numerically.

<?php
    $games = array(
        "Farcry 4",
        "Metal Gear",
        "Fallout 4",
        "Witcher 3",
        "Batman");
    sort($games); // array to sort
    echo join(", ", $games);
    //output - Batman, Fallout 4, Farcry 4, Metal Gear, Witcher 3
?>

In order to echo or print out sorted arrays we can use a function called join() which is an alias of another function called implode().

join(glue, array) or implode(glue, array) functions return a string from the elements of an array and both have the same syntax.

  • glue – (optional) also known as a separator is what to put between the array elements.
  • array – (required) is the array to join to a string.

If you need to sort and reverse the order of any array then you can use a function called rsort(). It works exactly the same way as sort() except the output is reversed.

<?php
    $games = array(
        "Farcry 4",
        "Metal Gear",
        "Fallout 4",
        "Witcher 3",
        "Batman");
    rsort($games); // array to sort
    echo join(", ", $games);
    //output - Witcher 3, Metal Gear, Farcry 4, Fallout 4, Batman
?>

Summarize

By now you should have a good overview of some common PHP functions for handling strings, integers and arrays.

Now for a simple exercise, the goal is:

  1. Create an array and put 5 elements in it.
  2. Sort and count the array.
  3. Randomly select an element from the array
  4. echo or print out the select item in upper or lower case.
<?php
    // create an array
    $new_games = array();
    $games = array_push($new_games,
        "Farcry 4",
        "Metal Gear",
        "Fallout 4",
        "Witcher 3",
        "Batman");
    // count number of items
    $total_items = count($new_games);
    // Sort the array
    sort($new_games);
    // Randomly select an item
    $selected = rand(0, $total_items);
    // echo or print in upper or lower case
    echo strtoupper($new_games[$selected]);
?>

Next: we will look at creating our own custom functions.

Matthew Horne

Matthew is a web developer from the United Kingdom who taught himself PHP and JavaScript and never looked back. If you would like to hire me, shoot me an email.