开发者

Array elements into variables

$data = array (                 
开发者_StackOverflow社区            'id'    => $_POST["id"],
            'name'  => $_POST["name"],
            'email' => $_POST["email"]
            );

Is there a single php function that can transform the array keys into variables having the value of the array value? For instance instead of echoing a value via echo $data['name'] I can simply use echo $name.

Please do not suggest solutions using foreach loops (if possible).


extract does just this: (docs)

 $size = "large";   
 $var_array = array("color" => "blue",
                       "size"  => "medium",
                       "shape" => "sphere");
 extract($var_array, EXTR_PREFIX_SAME, "wddx");

 echo "$color, $size, $shape, $wddx_size\n";

list does as well, in a more controlled fashion (docs), just note that your source array must be numerically indexed - no associative arrays allowed here:

    $info = array('coffee', 'brown', 'caffeine');

    // Listing all the variables
    list($drink, $color, $power) = $info;
    echo "$drink is $color and $power makes it special.\n";


extract($_POST);

http://www.php.net/manual/en/function.extract.php


http://php.net/manual/fr/function.list.php

You're maybe looking for the list function, so you know which variable you are dealing with.

list($var, $var2) = $_POST;


A foreach loop in this case is actually a pretty compact solution...

foreach ( $data as $key => $value ) { $$key = $value; }

Although, simply referencing the array by key is fairly tidy in and of itself...

echo $data['id'];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜