Using the Power of In-Built Controls

Using the Power of In-Built Controls

Welcome back! You've journeyed through crafting custom functions, mastering parameter handling, tracking variable scopes, and even exploring recursion. Today, we are going to tap into the powerful built-in functions that PHP offers. These functions are like advanced tools that help us execute common tasks effectively and efficiently. Are you excited to see what these functions can do for us? Let’s dive in!

What You'll Learn

In this unit, we will focus on how built-in functions in PHP can significantly simplify our code. By the end of this unit, you'll understand how to:

  • Use array-related functions to manipulate arrays.
  • Count elements, shift elements, and reverse arrays.
  • Find maximum values in associative arrays.

To give you a preview, consider this detailed example:

Defining and Printing the Array

<?php
// Defining array of planets
$planets = array("Mercury", "Venus", "Earth", "Mars");

// Function to display a full array 
print_r($planets);
?>

Here, the print_r function is employed to display the contents of the array, providing a quick and readable overview of the planets array.

Output:

Array
(
    [0] => Mercury
    [1] => Venus
    [2] => Earth
    [3] => Mars
)

Removing the Last Element

<?php
// Removing the last element
array_pop($planets);
echo "After removing the last planet:\n";
print_r($planets);
?>

The array_pop function removes the last element from the array as displayed in the output.

Output:

After removing the last planet:
Array
(
    [0] => Mercury
    [1] => Venus
    [2] => Earth
)

Removing the First Element

<?php
// Removing the first element
array_shift($planets);
echo "After removing the first planet:\n";
print_r($planets);
?>

On the other hand the array_shift function is used to eliminate the first element from the array.

Output:

After removing the first planet:
Array
(
    [0] => Venus
    [1] => Earth
)

Reversing the Array

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal