php - 带字符串的不同变量,一个数组

时间:2016-12-18 10:39:35

标签: php

以下是我的变数:

$a = Hello Mister
$b = I play basketball
$c = You walk in the city
$d = My name is Mary
$e = Where is Bryan

我当然尝试了爆炸“”,但它不起作用,因为每个变量都有空格的单词。 我还尝试调整chunk_split和str_split,但没有成功。 (...)

3 个答案:

答案 0 :(得分:0)

解决方案是:

  • 将变量名称保存在数组中,如下所示:

    $varArray = array('a', 'b', 'c', 'd', 'e');
    
  • 创建一个空结果数组,如下所示:

    $resultArray = array();
    
  • 使用$varArray循环遍历此变量数组foreach。在每次迭代中,使用variable variables获取字符串并将其附加到结果数组$resultArray,如下所示:

    foreach($varArray as $v){
        $resultArray[] = $$v;
    }
    

这是完整的代码:

$a = 'Hello Mister';
$b = 'I play basketball';
$c = 'You walk in the city';
$d = 'My name is Mary';
$e = 'Where is Bryan';

$varArray = array('a', 'b', 'c', 'd', 'e');
$resultArray = array();

foreach($varArray as $v){
    $resultArray[] = $$v;
}

// display $resultArray
var_dump($resultArray);

答案 1 :(得分:0)

您可以简单地在数组中添加以逗号分隔的变量,请参阅下面的示例:

$arr = array($a, $b, $c);

或者你也可以附加新发现的变量如下:

$arr[] = $d;

答案 2 :(得分:0)

你可以非常简单地做到这一点。

$a = "Hello Mister";
$b = "I play basketball";
$c = "You walk in the city";
$d = "My name is Mary";
$e = "Where is Bryan";

$sentence = array($a,$b,$c,$d,$e);

// or index can be assigned manually
$sentence[0] = $a;
$sentence[1] = $b;
$sentence[2] = $c;
$sentence[3] = $d;

// you can add new variable like below. And indexing automatically maintain sequence by itself.



$sentence[]  = $e;

echo "<pre>";
print_r($sentence);
echo "</pre>";

// output Array ( [0] => Hello Mister [1] => I play basketball [2] => You walk in the city [3] => My name is Mary [4] => Where is Bryan )

如果您对此有任何疑问,可以免费询问。谢谢