PHP - Converting an Array to a List of Variables

Introduction

list() can pull out the values of an array into separate variables.

Demo

<?php

$myBook = array("Java","John A", 2018);

$title = $myBook[0];/*from  w  w w . j  a  v  a 2 s  .  co  m*/
$author = $myBook[1];
$pubYear = $myBook[2];

echo $title."\n";    // Displays"Java"
echo $author."\n";   // Displays"John A"
echo $pubYear."\n";  // Displays"2018"
?>

Result

To use list() function:

Demo

<?php
$myBook = array("Java","John A", 2018);
list($title, $author, $pubYear) = $myBook;

echo $title."\n";    // Displays"Java"
echo $author."\n";   // Displays"John A"
echo $pubYear."\n";  // Displays"2018"
?>/*  ww w . j  a  va2  s . co  m*/

Result

list() only works with indexed arrays, and it assumes the elements are indexed consecutively starting from zero.

You can use list() with each() to return an indexed array of values.

Demo

<?php
            $myBook = array("title"=> "Java",
                            "author"=> "John A",
                            "pubYear"=>  2018);

            while (list($key, $value) = each($myBook)) {
              echo"$key \n";
              echo"$value \n";
            }//ww  w  .j a va  2s.  c  o  m
?>

Result

Related Topic