Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • The list() function and its uses in PHP 7.1

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 411
    Comment on it

    The function, list() is used to assign a list of variables in one operation only as if they were an array.

     

     

    In php7.1 list() function will not assign variables in reverse order.

     

    The syntax of the list() function is:

    list($array1, $array2, $array3) = array(value1,value2,value3);


    Example:

    list($array[],$array[],$array[]) = [1,2,3,];
    var_dump($array);
    // in php7.1 results in $array = [1,2,3] not in $array = [3,2,1].

     

    prior, in php 5.4 a short array syntax was used which made array easier to use and now in php7.1 instead of using list() function syntax we can use square brackets "[]" to assign variables from array..

    Means you can use any of the way, either list() or square brackets [].

    let's see the simple example:

    list($firstName, $lastName) = ["John", "Doe"];
    
    /*
    equivalent to :
    $firstName = "John";
    $lastName =  "Doe";
    */
    
    //or
    
    [$firstName, $lastName] = ["John", "Doe"];

     

     

    The list() function now have a great feature that is, It supports keys in list before that only numerical indexed arrays were used. Now list function also support associative arrays.

    Example:

    $user = [ "first_name" => "John", "last_name" => "Doe"];
    ["first_name" => $firstName, "last_name" => $lastName]= $user;

     

     

    We can also define multidimensional arrays inside list function as:

    Example:

    $users = [
        ["name" => "John Doe", "age" => 29],
        ["name" => "Sam", "age" => 36]
    ];
    [["name" => $name1, "age" => $age1],["name" => $name2, "age" => $age2]] = $users;

     

    The list constructs now not allowed to be assigned as empty and unpacked.

    Example:

    list() = $a;
    //empty array not allowed.

     

    The list() function and its uses in PHP 7.1

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: