Category: PHP

  • Call by Value

    By default, PHP uses the “call by value” mechanism for passing arguments to a function. When a function is called, the values of actual arguments are copied to the formal arguments of the function’s definition.

    During the execution of the function body, if there is any change in the value of any of the formal arguments, it is not reflected in the actual arguments.

    Types of Arguments in PHP Functions

    Here are the two types of arguments used in PHP functions −

    • Actual Arguments − The arguments that are passed in a function call.
    • Formal Arguments − The arguments that are declared in a function definition.

    Syntax

    Here is the way you can define actual and formal arguments in PHP:

    <?php 
       // $name is a formal argument
       function greet($name) {  
    
    echo "Hello, $name!";
    } // Rahul is an actual argument greet("Rahul"); ?>

    Demonstrating Call by Value

    Let us consider the function used in the code below −

    <?php  
       function change_name($nm) {
    
      echo "Initially the name is $nm \n";
      $nm = $nm."_new";
      echo "This function changes the name to $nm \n";
    } $name = "John"; echo "My name is $name \n"; change_name($name); echo "My name is still $name"; ?>

    Output

    It will produce the following result −

    My name is John
    Initially the name is John
    This function changes the name to John_new
    My name is still John
    

    In this example, the change_name() function appends _new to the string argument passed to it. However, the value of the variable that was passed to it remains unchanged after the function’s execution.

    Formal arguments, in fact, behave as local variables for the function. Such a variable is accessible only inside the scope in which it is initialized. For a function, its body marked by the curly brackets “{ }” is its scope. Any variable inside this scope is not available for the code outside it. Hence, manipulation of any local variable has no effect on the world outside.

    The “call by value” method is suitable for a function that uses the values passed to it. It performs certain computation and returns the result without having to change the value of parameters passed to it.

    Note − Any function that performs a formula-type computation is an example of call by value.

    Example 1

    Take a look at the following example −

    <?php
       function addFunction($num1, $num2) {
    
      $sum = $num1 + $num2;
      return $sum;
    } $x = 10; $y = 20; $num = addFunction($x, $y); echo "Sum of the two numbers is : $num"; ?>

    Output

    It will generate the following output −

    Sum of the two numbers is : 30  
    

    Example 2

    Here is another example of calling a function by passing the argument by value. The function increments the received number by 1, but that doesn’t affect the variable passed to it.

    <?php
       function increment($num) {
    
      echo "The initial value: $num \n";
      $num++;
      echo "This function increments the number by 1 to $num \n";
    } $x = 10; increment($x); echo "Number has not changed: $x"; ?>

    Output

    It will produce the following outcome −

    The initial value: 10
    This function increments the number by 1 to 11
    Number has not changed: 10
    

    Example 3

    In the below example we will be incrementing a value and we will not change the original variable.

    <?php
       function increment($num) {
    
      echo "The initial value: $num \n";
      $num++;
      echo "This function increments the number by 1 to $num \n";
    } $x = 10; increment($x); echo "Number has not changed: $x"; ?>

    Output

    It will generate the following outcome −

    The initial value: 10 
    This function increments the number by 1 to 11 
    Number has not changed: 10
    

    String Manipulation in Call by Value

    In php, we can also manipulate strings using call by value. In our example we will append a string by passing a value in the argument.

    <?php
       function appendString($str) {
    
      $str .= " World!";
      echo "Inside function: $str\n";
    } $text = "Hello"; appendString($text); // Original string remains unchanged echo "Outside function: $text"; ?>

    Output

    It will generate the following outcome −

    Inside function: Hello World!
    Outside function: Hello
    

    PHP also supports passing the reference of variables to the function while calling. We shall discuss it in the next chapter.

  • Function Parameters

    Function Parameters in PHP

    A function in PHP may be defined to accept one or more parameters. Function parameters are a comma-separated list of expressions inside the parenthesis in front of the function name while defining a function. A parameter may be of any scalar type (number, string or Boolean), an array, an object, or even another function.

    Syntax

    Here is the syntax for defining parameters in PHP functions −

    functionfoo($arg_1,$arg_2,$arg_n){
       statements;return$retval;}

    The arguments act as the variables to be processed inside the function body. Hence, they follow the same naming conventions as any normal variable, i.e., they should start with “$” and can contain alphabets, digits and underscore.

    Note − There is no restriction on how many parameters can be defined.

    Functions Call with Parameters

    When a parameterized function needs to be called, you have to make sure that the same number of values as in the number of arguments in function’s definition, are passed to it.

    foo(val1, val2, val_n);

    A function defined with parameters can produce a result that changes dynamically depending on the passed values.

    Default Parameters in PHP

    Here is the way you can set default values for function parameters in PHP so that arguments become optional.

    <?php
       function greet($name = "Guest") {
    
      echo "Hello, $name!";
    } greet(); echo "\n"; greet("Rashmi"); ?>

    Output

    It will produce the below result −

    Hello, Guest!
    Hello, Rashmi!
    

    Variable Length Arguments in PHP

    In PHP, you can also define variable-length parameters if you do not know the number of parameters in advanced. Here is the way you can create functions that accept a dynamic number of arguments using ‘….’.

    <?php
       function sumAll(...$numbers) {
    
      return array_sum($numbers);
    } echo sumAll(1, 2, 3, 4); ?>

    Output

    It will generate the below result −

    10
    

    Function to Add Two Numbers

    The following code contains the definition of addition() function with two parameters, and displays the addition of the two. The run-time output depends on the two values passed to the function.

    <?php
       function addition($first, $second) {
    
      $result = $first+$second;
      echo "First number: $first \n";
      echo "Second number: $second \n"; 
      echo "Addition: $result";
    } addition(10, 20); $x=100; $y=200; addition($x, $y); ?>

    Output

    It will generate the following output −

    First number: 10 
    Second number: 20 
    Addition: 30 
    First number: 100 
    Second number: 200 
    Addition: 300
    

    Formal and Actual Arguments

    Sometimes the term argument is used for parameter. Actually, the two terms have a certain difference.

    • A parameter refers to the variable used in function’s definition, whereas an argument refers to the value passed to the function while calling.
    • An argument may be a literal, a variable or an expression
    • The parameters in a function definition are also often called as formal arguments, and what is passed is called actual arguments.
    • The names of formal arguments and actual arguments need not be same. The value of the actual argument is assigned to the corresponding formal argument, from left to right order.
    • The number of formal arguments defined in the function and the number of actual arguments passed should be same.

    Example

    PHP raises an ArgumentCountError when the number of actual arguments is less than formal arguments. However, the additional actual arguments are ignored if they are more than the formal arguments.

    <?php
       function addition($first, $second) {
    
      $result = $first+$second;
      echo "First number: $first \n";
      echo "Second number: $second \n";
      echo "Addition: $result \n";
    } # Actual arguments more than formal arguments addition(10, 20, 30); # Actual arguments fewer than formal arguments $x=10; $y=20; addition($x); ?>

    Output

    It will produce the below output −

    First number: 10 
    Second number: 20 
    Addition: 30 
    PHP Fatal error:  Uncaught ArgumentCountError: Too few arguments
    to function addition(), 1 passed in /home/cg/root/20048/main.php
    on line 16 and exactly 2 expected in /home/cg/root/20048/main.php:2
    

    Arguments Type Mismatch

    PHP is a dynamically typed language, hence it doesn’t enforce type checking when copying the value of an actual argument with a formal argument. However, if any statement inside the function body tries to perform an operation specific to a particular data type which doesn’t support it, PHP raises an exception.

    In the addition() function above, it is assumed that numeric arguments are passed. PHP doesn’t have any objection if string arguments are passed, but the statement performing the addition encounters exception because the “+” operation is not defined for string type.

    Type Error with String Arguments

    Take a look at the following example −

    <?php
       function addition($first, $second) {
    
      $result = $first+$second;
      echo "First number: $first \n";
      echo "Second number: $second \n";
      echo "Addition: $result";
    } # Actual arguments are strings $x="Hello"; $y="World"; addition($x, $y); ?>

    Output

    It will create the following outcome −

    PHP Fatal error:  Uncaught TypeError: Unsupported operand types: string + string in hello.php:5
    

    However, PHP is a weakly typed language. It attempts to cast the variables into compatible type as far as possible. Hence, if one of the values passed is a string representation of a number and the second is a numeric variable, then PHP casts the string variable to numeric in order to perform the addition operation.

    Automatic Type Conversion

    Take a look at the following example −

    <?php
       function addition($first, $second) {
    
      $result = $first+$second;
      echo "First number: $first \n";
      echo "Second number: $second \n";
      echo "Addition: $result";
    } # Actual arguments are strings $x="10"; $y=20; addition($x, $y); ?>

    Output

    It will produce the following output −

    First number: 10 
    Second number: 20 
    Addition: 30
    
  • Functions

    Like most of the programming languages, a function in PHP is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reuse.

    PHP supports a structured programming approach by arranging the processing logic by defining blocks of independent reusable functions. The main advantage of this approach is that the code becomes easy to follow, develop and maintain.

    The following figure shows how the process of salary computation is successively broken down to independent and reusable functions.

    PHP Functions

    Types of Functions

    You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well. There are two types of functions in PHP −

    • Built-in functions − PHP’s standard library contains a large number of built-in functions for string processing, file IO, mathematical computations and more.
    • User-defined functions − You can create user-defined functions too, specific to the requirements of the programming logic.

    A function may be invoked from any other function by passing required data (called parameters or arguments). The called function returns its result back to the calling environment.

    There are two parts which should be clear to you −

    • Creating a PHP Function
    • Calling a PHP Function

    In fact you hardly need to create your own PHP function because there are already more than 1000 built-in library functions created for different area and you just need to call them according to your requirement.

    Please refer to PHP Function Reference for a complete set of useful functions.

    Why Use Functions?

    Here are some of the reasons provided to explain why you should use functions −

    • Reusable code is defined as code that can be written once and used repeatedly.
    • Breaking code into smaller parts makes it easier to maintain.
    • Functions clarify and arrange the code.

    Creating a Function in PHP

    Now let’s understand the process in detail. The first step is to write a function and then you can call it as many times as required.

    To create a new function, use the function keyword, followed by the name of the function you may want to use. In front of the name, put a parenthesis, which may or may not contain arguments.

    It is followed by a block of statements delimited by curly brackets. This function block contains the statements to be executed every time the function is called. The general syntax of defining a function is as follows −

    <?php   
       function foo($arg_1, $arg_2, $arg_n) {
    
      statements;
      return $retval;
    } ?>

    If the function is intended to return some result back to the calling environment, there should be a return statement as the last statement in the function block. It is not mandatory to have a return statement, as even without it, the program flow goes back to the caller, albeit without carrying any value with it.

    Any valid PHP code may appear inside a function, even other functions and class definitions. Name of the function must follow the same rules as used to form the name of a variable. It should start with a letter or underscore, followed by any number of letters, numbers, or underscores.

    Here is a simple function in PHP. Whenever called, it is expected to display the message “Hello World”.

    functionsayhello(){echo"Hello World";}

    User-defined Functions in PHP

    Its very easy to create your own PHP function. Let’s start with a simple example after which we will elaborate how it works. Suppose you want to create a PHP function which will simply write a simple message on your browser when you will call it.

    Example

    In this example, we create a function called writeMessage() and then call it to print a simple message −

    <?php
       /* Defining a PHP Function */
       function writeMessage() {
    
      echo "You are really a nice person, Have a nice time!";
    } /* Calling a PHP Function */ writeMessage(); ?>

    Output

    It will produce the following output −

    You are really a nice person, Have a nice time!
    

    Calling a Function in PHP

    Once a function is defined, it can be called any number of times, from anywhere in the PHP code. Note that a function will not be called automatically.

    To call the function, use its name in a statement; the name of the function followed by a semicolon.

    <?php
       # define a function
       function sayhello(){
    
      echo "Hello World";
    } # calling the function sayhello(); ?>

    Output

    It will produce the following output −

    Hello World
    

    Assuming that the above script “hello.php” is present in the document root folder of the PHP server, open the browser and enter the URL as http://localhost/hello.php. You should see the “Hello World” message in the browser window.

    In this example, the function is defined without any arguments or any return value. In the subsequent chapters, we shall learn about how to define and pass arguments, and how to make a function return some value. Also, some advanced features of PHP functions such as recursive functions, calling a function by value vs by reference, etc. will also be explained in detail.

    Additional Key Concepts in PHP Functions

    Here are the key concepts used in php functions −

    • Function Parameters and Arguments: Pass data to functions and specify default values.
    • Return Values: Use return to send the results back to the caller.
    • Variable Scope: Understand local and global variables, as well as the global keyword.
    • Anonymous Functions: Create functions with no names (closures).
    • Built-in Functions: Use PHP’s pre-defined functions (such as strlen() and date()).
    • Recursive Functions: The functions are those that call themselves (for example, factorial calculation).
    • Function Overloading: func_get_args() accepts multiple parameters.
    • Passing by Reference: Use & to modify variables directly.
    • Type declarations: Enforce the argument and return types (int, string).
    • Error Handling: Manage errors with try, catch, and exceptions.
  • Constant Arrays

    In PHP, an array is a collection of elements that can have several values under a single name. Normally, arrays in PHP are mutable, which means you can add, remove or change elements after they are generated. Constant arrays, on the other hand, are useful when you want an array with values that never change during your program.

    A constant array is one that cannot be altered once defined. You have access to its components, but you cannot modify, add or remove them. Prior to PHP 5.6, it was not possible to declare constant arrays; however, current versions of PHP introduced simple methods to perform this using the const keyword or the define() function.

    Unlike a normal array, its identifier doesn’t start with the “$” sign.

    Syntax of the Constant Arrays

    The syntax for declaring constant array using const is −

    constARRAY_NAME=["val1","val2","val3"];

    The syntax for defining constant array using define() is −

    define('ARRAY_NAME',["val1","val2","val3"]);

    Constant Array with const

    In the below example we have used const to define the constant array and displayed using the var_dump() function.

    <?php
       const FRUITS = array(
    
      "Watermelon", 
      "Strawberries",
      "Pomegranate",
      "Blackberry",
    ); var_dump(FRUITS); ?>

    Output

    It will generate the following output −

    array(4) {
       [0]=>
       string(10) "Watermelon"
       [1]=>
       string(12) "Strawberries"
       [2]=>
       string(11) "Pomegranate"
       [3]=>
       string(10) "Blackberry"
    }
    

    You can also use the conventional square bracket syntax to declare a constant array in PHP −

    constFRUITS=["Watermelon","Strawberries","Pomegranate","Blackberry",];

    Try to Modify the Constant Array

    It is not possible to modify any element in a constant array. Hence, the following code throws a fatal error −

    <?php
       const FRUITS = [
    
      "Watermelon", 
      "Strawberries",
      "Pomegranate",
      "Blackberry",
    ]; FRUITS[1] = "Mango"; ?>

    Output

    It will produce the following output −

    PHP Fatal error:  Cannot use temporary expression in write context
    

    Constant Arrays PHP 7 Onwards (With define())

    The newer versions of PHP allow you to declare a constant array with define() function.

    <?php
       define ('FRUITS',  [
    
      "Watermelon", 
      "Strawberries",
      "Pomegranate",
      "Blackberry",
    ]); print_r(FRUITS); ?>

    Output

    It will produce the following output −

    Array
    (
       [0] => Watermelon
       [1] => Strawberries
       [2] => Pomegranate
       [3] => Blackberry
    )
    

    You can also use the array() function to declare the constant array here.

    define('FRUITS',array("Watermelon","Strawberries","Pomegranate","Blackberry",));

    Associative Constant Array with define()

    It is also possible to declare an associative constant array. Here is an example −

    <?php
       define ('CAPITALS',  array(
    
      "Maharashtra" =&gt; "Mumbai",
      "Telangana" =&gt; "Hyderabad",
      "Gujarat" =&gt; "Gandhinagar",
      "Bihar" =&gt; "Patna"
    )); print_r(CAPITALS); ?>

    Output

    It will produce the following output −

    Array
    (
       [Maharashtra] => Mumbai
       [Telangana] => Hyderabad
       [Gujarat] => Gandhinagar
       [Bihar] => Patna
    )
    

  • Array Functions

    PHP Array Functions allow you to interact with and manipulate arrays in various ways. PHP arrays are essential for storing, managing, and operating on sets of variables.

    PHP supports simple and multi-dimensional arrays and can be either user created or created by another function. You can use these functions to modify, sort, add, remove or search elements in an array.

    Installation

    There is no installation needed to use PHP array functions; they are part of the PHP core and comes along with standard PHP installation.

    Runtime Configuration

    This extension has no configuration directives defined in php.ini.

    PHP Array Functions

    Following table lists down all the functions related to PHP Array. Here column version indicates the earliest version of PHP that supports the function.

    Sr.NoFunction & DescriptionVersion
    1array()Create an array4.2.0
    2array_change_key_case()Returns an array with all keys in lowercase or uppercase4.2.0
    3array_chunk()Splits an array into chunks of arrays4.2.0
    3array_column()Return the values from a single column in the input array5.5.0
    4array_combine()Creates an array by using one array for keys and another for its values5
    5array_count_values()Returns an array with the number of occurrences for each value4
    6array_diff()Compares array values, and returns the differences4
    7array_diff_assoc()Compares array keys and values, and returns the differences4
    8array_diff_key()Compares array keys, and returns the differences5
    9array_diff_uassoc()Compares array keys and values, with an additional user-made function check, and returns the differences5
    10array_diff_ukey()Compares array keys, with an additional user-made function check, and returns the differences5
    11array_fill()Fills an array with values4
    12array_fill_keys()Fill an array with values, specifying keys5
    13array_filter()Filters elements of an array using a user-made function4
    14array_flip()Exchanges all keys with their associated values in an array4
    15array_intersect()Compares array values, and returns the matches4
    16array_intersect_assoc()Compares array keys and values, and returns the matches4
    17array_intersect_key()Compares array keys, and returns the matches5
    18array_intersect_uassoc()Compares array keys and values, with an additional user-made function check, and returns the matches5
    19array_intersect_ukey()Compares array keys, with an additional user-made function check, and returns the matches5
    20array_key_exists()Checks if the specified key exists in the array4
    21array_keys()Returns all the keys of an array4
    22array_map()Sends each value of an array to a user-made function, which returns new values4
    23array_merge()Merges one or more arrays into one array4
    24array_merge_recursive()Merges one or more arrays into one array4
    25array_multisort()Sorts multiple or multi-dimensional arrays4
    26array_pad()Inserts a specified number of items, with a specified value, to an array4
    27array_pop()Deletes the last element of an array4
    28array_product()Calculates the product of the values in an array5
    29array_push()Inserts one or more elements to the end of an array4
    30array_rand()Returns one or more random keys from an array4
    31array_reduce()Returns an array as a string, using a user-defined function4
    32array_reverse()Returns an array in the reverse order4
    33array_search()Searches an array for a given value and returns the key4
    34array_shift()Removes the first element from an array, and returns the value of the removed element4
    35array_slice()Returns selected parts of an array4
    36array_splice()Removes and replaces specified elements of an array4
    37array_sum()Returns the sum of the values in an array4
    38array_udiff()Compares array values in a user-made function and returns an array5
    39array_udiff_assoc()Compares array keys, and compares array values in a user-made function, and returns an array5
    40array_udiff_uassoc()Compares array keys and array values in user-made functions, and returns an array5
    41array_uintersect()Compares array values in a user-made function and returns an array5
    42array_uintersect_assoc()Compares array keys, and compares array values in a user-made function, and returns an array5
    43array_uintersect_uassoc()Compares array keys and array values in user-made functions, and returns an array5
    44array_unique()Removes duplicate values from an array4
    45array_unshift()Adds one or more elements to the beginning of an array4
    46array_values()Returns all the values of an array4
    47array_walk()Applies a user function to every member of an array3
    48array_walk_recursive()Applies a user function recursively to every member of an array5
    49arsort()Sorts an array in reverse order and maintain index association3
    50asort()Sorts an array and maintain index association3
    51compact()Create array containing variables and their values4
    52count()Counts elements in an array, or properties in an object3
    53current()Returns the current element in an array3
    54each()Returns the current key and value pair from an array3
    55end()Sets the internal pointer of an array to its last element3
    56extract()Imports variables into the current symbol table from an array3
    57in_array()Checks if a specified value exists in an array4
    58key()Fetches a key from an array3
    59krsort()Sorts an array by key in reverse order3
    60ksort()Sorts an array by key3
    61list()Assigns variables as if they were an array3
    62natcasesort()Sorts an array using a case insensitive “natural order” algorithm4
    63natsort()Sorts an array using a “natural order” algorithm4
    64next()Advance the internal array pointer of an array3
    65pos()Alias of current()3
    66prev()Rewinds the internal array pointer3
    67range()Creates an array containing a range of elements3
    68reset()Sets the internal pointer of an array to its first element3
    69rsort()Sorts an array in reverse order3
    70shuffle()Shuffles an array3
    71sizeof()Alias of count()3
    72sort()Sorts an array3
    73uasort()Sorts an array with a user-defined function and maintain index association3
    74uksort()Sorts an array by keys using a user-defined function3
    75usort()Sorts an array by values using a user-defined function3

    PHP Array Constants

    Sr.NoConstant & Description
    1CASE_LOWERUsed with array_change_key_case() to convert array keys to lower case
    2CASE_UPPERUsed with array_change_key_case() to convert array keys to upper case
    3SORT_ASCUsed with array_multisort() to sort in ascending order
    4SORT_DESCUsed with array_multisort() to sort in descending order
    5SORT_REGULARUsed to compare items normally
    6SORT_NUMERICUsed to compare items numerically
    7SORT_STRINGUsed to compare items as strings
    8SORT_LOCALE_STRINGUsed to compare items as strings, based on the current locale
    9COUNT_NORMAL
    10COUNT_RECURSIVE
    11EXTR_OVERWRITE
    12EXTR_SKIP
    13EXTR_PREFIX_SAME
    14EXTR_PREFIX_ALL
    15EXTR_PREFIX_INVALID
    16EXTR_PREFIX_IF_EXISTS
    17EXTR_IF_EXISTS
    18EXTR_REFS
  • Multidimensional Array

    A multidimensional array is an array of arrays. In a PHP array, each element can be another array. If the array consists of values or key-value pairs with values being of singular scalar types, it is a one-dimensional array. If each element in an array is an array of one or more scalar values, it is a two-dimensional array.

    A PHP array may be a two-dimensional associative array also, where each element of the outer array is key-value pair, the value being another associative array.

    Syntax

    Here is the Syntax for one dimensional indexed array −

    # one dimensional indexed array$arr=[10,20,30,40];

    Following is the Syntax for one dimensional associative array −

    # one dimensional associative array$arr=["key1"=>"val1","key2"=>"val2","key3"=>"val3"];

    Here is the Syntax for two dimensional indexed array −

    # two dimensional indexed array$arr=[[1,2,3,4],[10,20,30,40],[100,200,300,400]];

    Below is the Syntax for two dimensional associative array −

    # two dimensional associative array$arr=["row1"=>["key11"=>"val11","key12"=>"val12","key13"=>"val13"],"row2"=>["key21"=>"val21","key22"=>"val22","key23"=>"val23"],"row3"=>["key31"=>"val31","key32"=>"val32","key33"=>"val33"]];

    Iterating over a 2D Array

    Two nested loops will be needed to traverse all the elements in a 2D array. The foreach loop is more suitable for array traversal. A 2D array is like a tabular representation of data in rows and columns.

    Traversing Indexed 2D Array

    The following example shows how you can reproduce a 2D array in a tabular form −

    <?php
       $tbl = [
    
      [1,2,3,4],
      [10, 20, 30, 40],
      [100, 200, 300, 400]
    ]; echo ("\n"); foreach ($tbl as $row){
      foreach ($row as $elem){
         $val = sprintf("%5d", $elem);
         echo $val;
      }
      echo "\n";
    } ?>

    Output

    It will produce the following output −

      1    2    3    4
     10   20   30   40
    100  200  300  400
    

    Traversing Associative 2D Array

    We can also employ two nested foreach loops to traverse a 2D associative array. Unpack each row of the outer array in row-key and row-value variables and traverse each row elements with the inner foreach loop.

    <?php
       $tbl = [
    
      "row1" =&gt; ["key11" =&gt; "val11", "key12" =&gt; "val12", "key13" =&gt; "val13"],
      "row2" =&gt; ["key21" =&gt; "val21", "key22" =&gt; "val22", "key23" =&gt; "val23"],
      "row3" =&gt; ["key31" =&gt; "val31", "key32" =&gt; "val32", "key33" =&gt; "val33"]
    ]; echo ("\n"); foreach ($tbl as $rk=>$rv){
      echo "$rk\n";
      foreach ($rv as $k=&gt;$v){
         echo "$k =&gt; $v  ";
      }
      echo "\n";
    } ?>

    Output

    It will produce the following output −

    row1
    key11 => val11  key12 => val12  key13 => val13
    row2
    key21 => val21  key22 => val22  key23 => val23
    row3
    key31 => val31  key32 => val32  key33 => val33
    

    Accessing the Elements in a 2D Array

    The $arr[$key] syntax of accessing and modifying an element in the array can be extended to a 2D array too. For a 2D indexed array, the jth element in the ith row can be fetched and assigned by using the expression “$arr[$i][$j]“.

    Indexed 2D Array

    <?php
       $tbl = [[1,2,3,4], [10, 20, 30, 40], [100, 200, 300, 400]];    
    
       # prints number in index 2 of the row 2
       print ("Value at [2], [2] :" . $tbl[2][2]);
    ?>

    Output

    It will produce the following output −

    Value at [2], [2] :300
    

    Similarly, the value at ith row and jth column may be set to another value.

    $tbl[2][2]=250;

    Associative 2D Array

    If it is a 2D associative array, we need to use the row key and key-value variables of the desired column to access or modify its value.

    <?php
       $tbl = [
       "row1" => ["key11" => "val11", "key12" => "val12", "key13" => "val13"],
       "row2" => ["key21" => "val21", "key22" => "val22", "key23" => "val23"],
       "row3" => ["key31" => "val31", "key32" => "val32", "key33" => "val33"]
       ];
    
       print "value at row2 - key22 is " . $tbl["row2"]["key22"];
    ?>

    Output

    It will produce the following output −

    value at row2 - key22 is val22
    

    Multi-dimensional Array

    In the above example, we had an array in which the associated value of each key was another collection of key-value pairs, and we call it as a 2D array. The concept can be extended to any number of levels. For example, if each element in the inner array associates its key to another array, it becomes a three-dimensional array.

    Declaring a 3D Array

    Here is an example of a three-dimensional array −

    $arr3D=[[[1,0,9],[0,5,6],[1,0,3]],[[0,4,6],[0,0,1],[1,2,7]],];

    Traversing a 3D Array

    To traverse such a 3D array, we need three nested foreach loops, as shown below −

    <?php
       $arr3D = [ 
    
      [[1, 0, 9],[0, 5, 6],[1, 0, 3]],
      [[0, 4, 6],[0, 0, 1],[1, 2, 7]],
    ]; foreach ($arr3D as $arr) {
      foreach ($arr as $row) {
         foreach ($row as $element) {
            echo "$element ";
         }
         echo "\n";
      }
      echo "\n";
    } ?>

    Output

    It will produce the following output −

    1 0 9
    0 5 6
    1 0 3
    
    0 4 6
    0 0 1
    1 2 7
    

    However, it is entirely possible to declare an array extending upto any number of dimensions. For that we need to have a generalized solution to traverse an array of any dimensions.

    Recurve Traversal of Multidimensional Array

    The following code shows a recursive function that calls itself if the value of a certain key is another array. If we pass any array as an argument to this function, it will be traversed, showing all the k-v pairs in it.

    functionshowarray($arr){foreach($arras$k=>$v){if(is_array($v)){showarray($v);}else{echo"$k => $v  ";}}echo"\n";}

    Example

    Let us pass the above 3D array $arr3D to it and see the result −

    <?php
       $arr3D = [ 
    
      [[1, 0, 9],[0, 5, 6],[1, 0, 3]],
      [[0, 4, 6],[0, 0, 1],[1, 2, 7]],
    ]; function showarray($arr){
      foreach ($arr as $k=&gt;$v){
         if (is_array($v)){
            showarray($v);
         } else {
            echo "$k =&gt; $v  ";
         }
      }
      echo "\n";
    } showarray($arr3D); ?>

    Output

    It will produce the following output −

    0 => 1  1 => 0  2 => 9
    0 => 0  1 => 5  2 => 6
    0 => 1  1 => 0  2 => 3
    0 => 0  1 => 4  2 => 6
    0 => 0  1 => 0  2 => 1
    0 => 1  1 => 2  2 => 7
    

    This recursive function can be used with any type of array, whether indexed or associative, and of any dimension.

    Example

    Let us use a 2D associative array as argument to showarray() function −

    <?php
       $tbl = [
    
      "row1" =&gt; ["key11" =&gt; "val11", "key12" =&gt; "val12", "key13" =&gt; "val13"],
      "row2" =&gt; ["key21" =&gt; "val21", "key22" =&gt; "val22", "key23" =&gt; "val23"],
      "row3" =&gt; ["key31" =&gt; "val31", "key32" =&gt; "val32", "key33" =&gt; "val33"]
    ]; function showarray($arr){
      foreach ($arr as $k=&gt;$v){
         if (is_array($v)){
            showarray($v);
         } else {
            echo "$k =&gt; $v  ";
         }
      }
      echo "\n";
    } showarray($tbl); ?>

    Output

    It will produce the following output −

    key11 => val11  key12 => val12  key13 => val13
    key21 => val21  key22 => val22  key23 => val23
    key31 => val31  key32 => val32  key33 => val33

  • Associative Array

    If each element in a PHP array is a key-value pair, such an array is called an associative array. In this type of array, each value is identified by its associated key and not an index. Associative arrays are used to implement data structures such as dictionary, maps, trees, etc.

    In PHP, the “=>” symbol is used to establish association between a key and its value.

    Syntax of Associative Array in PHP

    Both the approaches of declaring an array – the array() function and the square bracket notation – can be used. The two syntaxes used to declare an associative array is given below.

    Using the array() function −

    $arr1=array("Maharashtra"=>"Mumbai","Telangana"=>"Hyderabad","UP"=>"Lucknow","Tamilnadu"=>"Chennai");

    Using the square bracket notation [] −

    $arr2=["Maharashtra"=>"Mumbai","Telangana"=>"Hyderabad","UP"=>"Lucknow","Tamilnadu"=>"Chennai"];

    Structure of the Associative Array

    If we call the var_dump() function, both the above arrays will show the similar structure −

    array(4){["Maharashtra"]=>string(6)"Mumbai"["Telangana"]=>string(9)"Hyderabad
       ["UP"]=>
       string(7) "Lucknow"
       ["Tamilnadu"]=>
       string(7) "Chennai"
    }

    The key part of each element in an associative array can be any number (integer, float or Boolean), or a string. The value part can be of any type. However, the float key is cast to an integer. So, a Boolean true/false is used as “1” or “0” as the key.

    Basic Example of Associative Array

    Take a look at the following example −

    <?php
       $arr1 = array(
    
      10=&gt;"hello",
      5.75=&gt;"world",
      -5=&gt;"foo",
      false=&gt;"bar"
    ); var_dump($arr1); ?>

    Output

    It will produce the following output −

    array(4) {
      [10]=>
      string(5) "hello"
      [5]=>
      string(5) "world"
      [-5]=>
      string(3) "foo"
      [0]=>
      string(3) "bar"
    }
    

    Note that the key 5.75 gets rounded to 5, and the key “true” is reflected as “0”. If the same key appears more than once in an array, the key-value pair that appears last will be retained, discarding the association of the key with earlier value.

    PHP internally treats even an indexed array as an associative array, where the index is actually the key of the value. It means the value at the 0th index has a key equal to “0”, and so on. A var_dump() on an indexed array also brings out this characteristics of a PHP array.

    Iterating an Associative Array

    foreach loop is the easiest and ideal for iterating through an associative array, although any other type of loop can also be used with some maneuver.

    Let us look at the foreach loop implementation, with each key value pair unpacked in two variables.

    <?php
       $capitals = array(
    
      "Maharashtra"=&gt;"Mumbai", 
      "Telangana"=&gt;"Hyderabad", 
      "UP"=&gt;"Lucknow", 
      "Tamilnadu"=&gt;"Chennai"
    ); foreach ($capitals as $k=>$v) {
      echo "Capital of $k is $v \n";
    } ?>

    Output

    It will produce the following output −

    Capital of Maharashtra is Mumbai
    Capital of Telangana is Hyderabad
    Capital of UP is Lucknow
    Capital of Tamilnadu is Chennai
    

    Using foreach with array_search()

    There is another way of using the foreach loop in PHP, where each element is stored in a variable. We can then separate the key and value parts using array_search() and use them in the loop body.

    <?php
       $capitals = array(
    
      "Maharashtra"=&gt;"Mumbai", 
      "Telangana"=&gt;"Hyderabad", 
      "UP"=&gt;"Lucknow", 
      "Tamilnadu"=&gt;"Chennai"
    ); foreach ($capitals as $pair) {
      $cap = array_search($pair, $capitals);         
      echo "Capital of $cap is $capitals[$cap] \n";
    } ?>

    Output

    It will produce the following output −

    Capital of Maharashtra is Mumbai 
    Capital of Telangana is Hyderabad 
    Capital of UP is Lucknow 
    Capital of Tamilnadu is Chennai
    

    To use for, while or do-while loop, we have to first get the array of all the keys (use array_keys()), find the size and use it as the test condition in the loop syntax.

    Using for loop with array_keys()

    Here is how we can use a for loop to traverse an associative array −

    <?php
       $capitals = array(
    
      "Maharashtra"=&gt;"Mumbai", 
      "Telangana"=&gt;"Hyderabad", 
      "UP"=&gt;"Lucknow",
      "Tamilnadu"=&gt;"Chennai"
    ); $keys=array_keys($capitals); for ($i=0; $i<count($keys); $i++){
      $cap = $keys[$i];
      echo "Capital of $cap is $capitals[$cap] \n";
    } ?>

    Output

    It will produce the following output −

    Capital of Maharashtra is Mumbai 
    Capital of Telangana is Hyderabad 
    Capital of UP is Lucknow 
    Capital of Tamilnadu is Chennai
    

    Accessing Values Using Keys

    In an associative array, the key is the identifier of value instead of index. Hence, to fetch value associated with a certain key, use $arr[key] syntax. The same can be used to update the value of a certain key.

    In the following code, an associative array $arr1 is declared. Another array $arr2 is created such that it stores each pair from $arr1 with the value of each key being doubled.

    <?php
       $arr1 = array("a"=>10, "b"=>20, "c"=>30, "d"=>40);
       foreach ($arr1 as $k=>$v){
    
      $arr2[$k] = $v*2;
    } print_r($arr2); ?>

    Output

    It will produce the following output −

    Array
    (
       [a] => 20
       [b] => 40
       [c] => 60
       [d] => 80
    )
    

    The print_r() function used here displays the data stored in the array in an easy to understand human readable form.

    Check if a Key Exists in an Associative Array

    In the following example, we are showing how you can loop for a key in an associative array. Before accessing a key, verify that it exists by calling array_key_exists() or isset().

    <?php
       $arr = ["a" => 10, "b" => 20];
    
       if (array_key_exists("a", $arr)) {
    
      echo "Key 'a' exists!";
    } ?>

    Output

    Following is the output of the above code −

    Key 'a' exists!
    

    Remove Elements from an Associative Array

    In the following example, we are using unset() function which can remove a specific key-value pair from an associative array.

    <?php
       $arr = ["a" => 10, "b" => 20, "c" => 30];
       unset($arr["b"]);
       print_r($arr);
    ?>

    Output

    Below is the output of the above code −

    Array ( [a] => 10 [c] => 30 )

  • Indexed Array

    In PHP, the array elements may be a collection of key-value pairs or it may contain values only. If the array consists of values only, it is said to be an indexed array, as each element is identified by an incrementing index, starting with “0”.

    Creating an Indexed Array

    An indexed array in PHP may be created either by using the array() function or with the square bracket syntax.

    $arr1=array("a",10,9.99,true);$arr2=["a",10,9.99,true];

    Structure of an Indexed Array

    Each element in the array has a positional index, the first element being at index “0”. The var_dump() function reveals the structured information of these arrays as −

    array(4){[0]=>string(1)"a"[1]=>int(10)[2]=>float(9.99)[3]=>bool(true)}

    We can use the index to traverse the array, fetch the value at a given index or modify the value of an element in place.

    Traversing an Indexed Array in PHP

    Any type of PHP loop can be employed to traverse an array. If we want to use a for or while loop, we have to find the number of elements in the array with count() function and use its value as the test condition for the counted for or while loop.

    Example

    The following code uses a for loop to list all the elements in an indexed array.

    <?php
       $numbers = array(10, 20, 30, 40, 50);
    
       for ($i=0; $i<count($numbers); $i++){
    
      echo "numbers[$i] = $numbers[$i] \n";
    } ?>

    It will produce the following output −

    numbers[0] = 10
    numbers[1] = 20
    numbers[2] = 30
    numbers[3] = 40
    numbers[4] = 50
    

    You can also use a while or do-while loop to traverse an indexed array. Here too, we need to find the array length with count() function.

    Example

    The following code traverses the given indexed array in reverse order −

    <?php
       $numbers = array(10, 20, 30, 40, 50);
       $i = count($numbers)-1;
       while ($i>=0){
    
      echo "numbers[$i] = $numbers[$i] \n";
      $i--;
    } ?>

    It will produce the following output −

    numbers[4] = 50
    numbers[3] = 40
    numbers[2] = 30
    numbers[1] = 20
    numbers[0] = 10
    

    Accessing the Array Elements Using Index

    You can access any value from an array using the array[index] syntax. The value at a specific index may be assigned with a new value. The array is thus modified in place.

    Example

    The following program fetches the values from an array $arr1 and places them in $arr2 in the reverse order. So the value at 0th position in $arr1 becomes the last value in $arr2.

    <?php
       $arr1 = array(10, 20, 30, 40, 50);
       $size = count($arr1);
    
       for ($i=0; $i<$size; $i++){
    
      $arr2[$size-$i-1] = $arr1[$i];
    } for ($i=0; $i<$size; $i++){
      echo "arr1[$i] = $$arr1[$i] arr2[$i] = $$arr2[$i] \n";
    } ?>

    It will produce the following output −

    arr1[0] = $10 arr2[0] = $50
    arr1[1] = $20 arr2[1] = $40
    arr1[2] = $30 arr2[2] = $30
    arr1[3] = $40 arr2[3] = $20
    arr1[4] = $50 arr2[4] = $10
    

    Traversing an Indexed Array Using “foreach” Loop

    You can also use the foreach loop to iterate through an indexed array. Take a look at the following example −

    <?php
       $arr1 = [10, 20, 30, 40, 50];
       foreach ($arr1 as $val){
    
      echo "$val \n";
    } ?>

    It will produce the following output −

    10 
    20 
    30 
    40 
    50
    

    Note that PHP internally treats the indexed array as an associative array, with the index being treated as the key. This fact can be verified by the var_dump() output of the array.

    Example

    We can unpack each element of an indexed array in the key and value variables with foreach syntax −

    <?php
       $arr1 = [10, 20, 30, 40, 50];
       foreach ($arr1 as $key => $val){
    
      echo "arr1[$key] = $val \n";
    } ?>

    It will produce the following output −

    arr1[0] = 10
    arr1[1] = 20
    arr1[2] = 30
    arr1[3] = 40
    arr1[4] = 50
    

    In PHP, an array may be a mix of only values and key-value pairs. PHP assigns the index only to the values without keys.

    Example

    In this example, PHP assigns incrementing index to the numbers, skipping the key-value pair appearing in it.

    <?php
       $arr1 = [10, 20, 
    
         "vals" =&gt; ["ten", "twenty"],
         30, 40, 50];
    var_dump($arr1); ?>

    It will produce the following output −

    array(6) {
      [0]=>
      int(10)
      [1]=>
      int(20)
      ["vals"]=>
      array(2) {
    
    [0]=&gt;
    string(3) "ten"
    [1]=&gt;
    string(6) "twenty"
    } [2]=> int(30) [3]=> int(40) [4]=> int(50) }

    Properties of Indexed Arrays

    Here are some of the properties of the indexed arrays are listed −

    • The initial element has an index of zero and grows sequentially.
    • An indexed array can store a wide range of values, like texts, numbers, floats and booleans.
    • Arrays in PHP can grow and decrease dynamically without being explicitly declared.
    • Indexed arrays can be easily looped using for or foreach loops.
    • PHP has several built-in functions for managing indexed arrays, like count($arr), array_push($arr, “Value”), and array_pop($arr).
  • Arrays

    An array is a data structure that stores one or more data values having some relation among them, in a single variable. For example, if you want to store the marks of 10 students in a class, then instead of defining 10 different variables, its easy to define an array of 10 length.

    Arrays in PHP behave a little differently than the arrays in C, as PHP is a dynamically typed language as against C which is a statically type language.

    How to Define an Array in PHP?

    In PHP, there are two ways to define an array: first using the array() function and second using the square brackets.

    The array() Function

    The built-in array() function uses the parameters given to it and returns an object of array type. One or more comma-separated parameters are the elements in the array.

    array(mixed...$values):array

    Each value in the parenthesis may be either a singular value (it may be a number, string, any object or even another array), or a key-value pair. The association between the key and its value is denoted by the “=>” symbol.

    Example

    Here is the example to show how you can use array() function in your programs −

    <?php
       $arr1 = array(10, "asd", 1.55, true);
       $arr2 = array("one"=>1, "two"=>2, "three"=>3);
       $arr3 = array(
    
      array(10, 20, 30),
      array("Ten", "Twenty", "Thirty"),
      array("physics"=&gt;70, "chemistry"=&gt;80, "maths"=&gt;90)
    ); print_r($arr3); ?>

    Output

    Following is the output of the above code −

    Array
    (
       [0] => Array
    
      (
         [0] =&gt; 10
         [1] =&gt; 20
         [2] =&gt; 30
      )
    [1] => Array
      (
         [0] =&gt; Ten
         [1] =&gt; Twenty
         [2] =&gt; Thirty
      )
    [2] => Array
      (
         [physics] =&gt; 70
         [chemistry] =&gt; 80
         [maths] =&gt; 90
      )
    )

    Using Square Brackets [ ]

    Instead of the array() function, the comma-separated array elements may also be put inside the square brackets to declare an array object. In this case too, the elements may be singular values or a string or another array.

    <?php
       $arr1 = [10, "asd", 1.55, true];
       $arr2 = ["one"=>1, "two"=>2, "three"=>3];
       $arr3 = [ [10, 20, 30],
    
      ["Ten", "Twenty", "Thirty"],
      ["physics"=&gt;70, "chemistry"=&gt;80, "maths"=&gt;90] ];
    ?>

    Example

    In this example, arr1 is an indexed array. However, var_dump()which displays the structured information of any object, shows that each value is having its index as its key.

    <?php
       $arr1 = [10, "asd", 1.55, true];
       var_dump($arr1);
    ?>

    Output

    It will produce the following result −

    array(4) {
      [0]=>
      int(10)
      [1]=>
      string(3) "asd"
      [2]=>
      float(1.55)
      [3]=>
      bool(true)
    }
    

    Example

    The same principle applies to a multi-dimensional index array, where each value in an array is another array.

    <?php
       $arr1 = [
    
      [10, 20, 30], 
      ["Ten", "Twenty", "Thirty"],
      [1.1, 2.2, 3.3]
    ]; var_dump($arr1); ?>

    Output

    It will produce the following outcome −

    array(3) {
      [0]=>
      array(3) {
    
    [0]=&gt;
    int(10)
    [1]=&gt;
    int(20)
    [2]=&gt;
    int(30)
    } [1]=> array(3) {
    [0]=&gt;
    string(3) "Ten"
    [1]=&gt;
    string(6) "Twenty"
    [2]=&gt;
    string(6) "Thirty"
    } [2]=> array(3) {
    [0]=&gt;
    float(1.1)
    [1]=&gt;
    float(2.2)
    [2]=&gt;
    float(3.3)
    } }

    Types of Arrays in PHP

    There are three different kind of arrays and each array value is accessed using an ID which is called the array index.

    • Indexed Array: An array which is a collection of values only is called an indexed array. Each value is identified by a positional index staring from “0”. Values are stored and accessed in linear fashion.For example -$fruits=[“Apple”,”Banana”,”Orange”];
    • Associative Array: If the array is a collection of key-value pairs, it is called as an associative array. The key component of the pair can be a number or a string, whereas the value part can be of any type. Associative arrays store the element values in association with key values rather than in a strict linear index order.$marks=[“Ankit”=>85,”Eisha”=>90,”Deepak”=>78];
    • Multi Dimensional Array − If each value in either an indexed array or an associative array is an array itself, it is called a multi dimensional array. Values are accessed using multiple indices.$students=[[“Ankit”,85,”A”],[“Eisha”,90,”A+”],[“Deepak”,78,”B”]];

    NOTE − Built-in array functions is given in function reference PHP Array Functions

    It may be noted that PHP internally considers any of the above types as an associative array itself. In case of an indexed array, where each value has index, the index itself is its key. The var_dump() function reveals this fact.

    Properties of Arrays in PHP

    Here are some properties of array −

    • An array in PHP is an ordered map that associates values to keys.
    • A PHP array can be used to implement different data structures such as a stack, queue, list (vector), hash table, dictionary, etc.
    • The value part of an array element can be other arrays. This fact can be used to implement tree data structure and multidimensional arrays.
    • PHP supports both indexed arrays (numeric keys) and associative arrays (string keys).
    • PHP provides many built-in functions for array manipulation, such as array_push(), array_pop(), array_merge(), etc.

    There are two ways to declare an array in PHP. One is to use the built-in array() function, and the other is to use a shorter syntax where the array elements are put inside square brackets.

    Accessing the Array Elements

    To access any element from a given array, you can use the array[key] syntax.

    Example

    For an indexed array, put the index inside the square bracket, as the index itself is anyway the key.

    <?php
       $arr1 = [10, 20, 30];
       $arr2 = array("one"=>1, "two"=>2, "three"=>3);
    
       var_dump($arr1[1]);
       var_dump($arr2["two"]);
    ?>

    Output

    It will produce the following output −

    int(20)
    int(2)
    

    We shall explore the types of PHP arrays in more details in the subsequent chapters.

  • Continue Statement

    Like the break statement, continue is another “loop control statement” in PHP. Unlike the break statement, the continue statement skips the current iteration and continues execution at the condition evaluation and then the beginning of the next iteration.

    The continue statement can be used inside any type of looping constructs, i.e., for, for-each, while or do-while loops. Like break, the continue keyword is also normally used conditionally.

    Syntax of Continue Statement

    The syntax of continue statement is as follows −

    while(expr){if(condition){continue;}}

    Flowchart for Continue Statement

    The following flowchart explains how the continue statement works −

    Php Continue Statement

    The program first checks a condition. If the condition is false, the loop terminates. If the condition is True, the program will proceed to the “Continue” statement.

    The “Continue” statement skips the next stages and returns to check the condition again. If there is no “continue” statement, the program will execute the action. When the action is finished, the program returns to check the condition again.

    Using Continue in For Loop

    Given below is a simple example showing the use of continue. The for loop is expected to complete ten iterations. However, the continue statement skips the iteration whenever the counter id is divisible by 2.

    <?php
       for ($x=1; $x<=10; $x++){
    
      if ($x%2==0){
         continue;
      }
      echo "x = $x \n";
    } ?>

    Output

    It will produce the following output −

    x = 1
    x = 3
    x = 5
    x = 7
    x = 9
    

    Using Continue with Multiple Loop

    The continue statement accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of. The default is 1.

    <?php
       for ($i=1; $i<=3; $i++){
    
      for ($j=1; $j&lt;=3; $j++){
         for ($k=1; $k&lt;=3; $k++){
            if ($k&gt;1){
               continue 2;
            }
            print "i: $i  j:$j  k: $k\n";
         }
      }
    } ?>

    Output

    It will generate the following result −

    i: 1  j:1  k: 1
    i: 1  j:2  k: 1
    i: 1  j:3  k: 1
    i: 2  j:1  k: 1
    i: 2  j:2  k: 1
    i: 2  j:3  k: 1
    i: 3  j:1  k: 1
    i: 3  j:2  k: 1
    i: 3  j:3  k: 1
    

    The continue statement in the inner for loop skips the iterations 2 and 3 and directly jumps to the middle loop. Hence, the output shows “k” as 1 for all the values of “i” and “k” variables.

    Skip Specific Values in For Loop

    In the code below, we will skip the values set in the for loop. In a loop that prints integers from 1 to 10, we will use the continue statement to skip the 5 number.

    <?php
       for ($i = 1; $i <= 10; $i++) {
    
      if ($i == 5) {
         // Skip when $i is 5
         continue; 
      }
      echo "Number: $i\n";
    } ?>

    Output

    This will create the below output −

    Number: 1
    Number: 2
    Number: 3
    Number: 4
    Number: 6
    Number: 7
    Number: 8
    Number: 9
    Number: 10
    

    Using Continue in a While Loop

    This example shows how to use the continue statement within a while loop to skip odd integers and only print even numbers from 1 to 10.

    <?php
       $num = 1;
       while ($num <= 10) {
    
      if ($num % 2 != 0) {
         $num++; 
         // Skip odd numbers
         continue; 
      }
      echo "Even Number: $num\n";
      $num++;
    } ?>

    Output

    Following is the output of the above code −

    Even Number: 2
    Even Number: 4
    Even Number: 6
    Even Number: 8
    Even Number: 10
    

    Skip Elements in a Foreach Loop

    In the following example, we are showing how to use the continue statement in a foreach loop to skip a specific value from an array.

    <?php
       $fruits = ["Apple", "Banana", "Mango", "Orange", "Grapes"];
    
      
    foreach ($fruits as $fruit) {
      if ($fruit == "Mango") {
         
         // Skip "Mango"
         continue; 
      }
      echo "Fruit: $fruit\n";
    } ?>

    Output

    Below is the output of the following code −

    Fruit: Apple
    Fruit: Banana
    Fruit: Orange
    Fruit: Grapes