Home > Articles > Programming > PHP

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Extracting Variables from Arrays

The extract function is handy for copying the elements in arrays to variables if your array is set up with string index values. For example, take a look at this case, where we have an array with string indexes:

$fruits["good"] = "tangerine";
$fruits["better"] = "pineapple";
$fruits["best"] = "pomegranate";
    .
    .
    .

When you call the extract function on this array, it creates variables corresponding to the string indexes: $good, $better, and so on:

$fruits["good"] = "tangerine";
$fruits["better"] = "pineapple";
$fruits["best"] = "pomegranate";

extract($fruits);
    .
    .
    .

Take a look at how this works in Example 3-3, phpextract.php.

Example 3-3. Extracting variables from an array, phpextract.php

<HTML>
        <HEAD>
            <TITLE>Extracting variables from an array</TITLE>
        </HEAD>

        <BODY>
            <H1>Extracting variables from an array</H1>
        <?php
            $fruits["good"] = "tangerine";
            $fruits["better"] = "pineapple";
            $fruits["best"] = "pomegranate";

            extract($fruits);

            
   echo "\$good = $good<BR>";
            
   echo "\$better = $better<BR>";
            
   echo "\$best = $best<BR>";
        ?>
    </BODY>
</HTML>

Now $good will hold "tangerine", $better will hold "pineapple", and $best will hold "pomegranate". You can see the results in Figure 3-3.

03fig03.gif

Figure 3-3 Filling variables from an array.

You can also use the PHP list function to get data from an array like this and store it in as many variables as you like. Here's an example:

<?php
    $vegetables[0] = "corn";
    $vegetables[1] = "broccoli";
    $vegetables[2] = "zucchini";
    list($first, $second) = $vegetables;
    echo $first, "\n";
    echo $second;
?>

And here is the result:

corn
broccoli

Can you go the opposite way and copy variables into an array? Sure, just use the compact function. You pass this function the names of variables (with the $), and compact finds those variables and stores them all in an array:

<?php
    $first_name  = "Cary";
    $last_name = "Grant";
    $role = "Actor";
    $subarray = array("first_name", "last_name");
    $resultarray = compact("role", $subarray);
?>
  • + Share This
  • 🔖 Save To Your Account