PHP将array()值设置为$variable


PHP get array() value to become $variable

好的,所以我有这个数组:

 $choices = array($_POST['choices']);

当使用var_dump()时,此输出:

array(1) { [0]=> string(5) "apple,pear,banana" }

我需要的是这些变量的值,以及作为字符串添加值。所以,我需要输出为:

 $apple = "apple";
 $pear = "pear";
 $banana = "banana";

数组的值可能会更改,因此必须根据该数组中的内容创建变量。

我将感谢所有的帮助。干杯

标记

怎么样

$choices = explode(',', $_POST['choices']);
foreach ($choices as $choice){
    $$choice = $choice;
}
$str = "apple,pear,pineapple";
$strArr = explode(',' , $str);
foreach ($strArr as $val) {
    $$val = $val;
}
var_dump($apple);

这将满足您的要求。然而,问题来了,因为你无法预先定义有多少变量和它们是什么,所以你很难正确使用它们。在使用$VAR之前测试"isset($VAR)"似乎是唯一安全的方法。

您最好只将源字符串拆分为一个数组,然后只操作特定数组的元素。

我不得不同意所有其他答案,认为这是一个非常糟糕的想法,但现有的每个答案都使用了一种有点迂回的方法来实现它。

PHP提供了一个函数extract,用于将数组中的变量提取到当前范围中。在这种情况下,您可以像这样使用它(首先使用爆炸和array_component将您的输入转换为关联数组):

$choices = $_POST['choices'] ?: ""; // The ?: "" makes this safe even if there's no input
$choiceArr = explode(',', $choices); // Break the string down to a simple array
$choiceAssoc = array_combine($choiceArr, $choiceArr); // Then convert that to an associative array, with the keys being the same as the values
extract($choiceAssoc, EXTR_SKIP); // Extract the variables to the current scope - using EXTR_SKIP tells the function *not* to overwrite any variables that already exist, as a security measure
echo $banana; // You now have direct access to those variables

有关为什么这是一种糟糕的方法的更多信息,请参阅关于现已弃用的register_globals设置的讨论。总之,它使编写不安全的代码变得容易得多。

在其他语言中经常被称为"split",在PHP中,您可能希望使用爆炸。

编辑:实际上,你想做的事情听起来。。。危险的这是可能的(也是PHP的一个老"特性"),但它非常令人沮丧。我建议将它们分解,并将它们的值作为关联数组的键:

$choices_assoc = explode(',', $_POST['choices']);
foreach ($choices as $choice) {
    $choices_assoc[$choice] = $choice;
}