如何在php中访问变量的值

时间:2016-02-26 14:10:46

标签: php

所以我有以下内容:

    $audio1_1 = "x";
    $audio2_1 = "z";
    $audio3_1 = "r";
    $audio4_1 = "b";
    $audio5_1 = "x";
    $audio6_1 = "z";
    $audio7_1 = "r";
    $audio8_1 = "b";

    for ($x = 1; $x <= 8; $x++) {
      //// what to put here to access the corresponding value???
    }

我的意思是当$ x = 1时我想获得$ audio1_1的值,当$ x = 2时我想获得$ audio2_1的值,依此类推。 谢谢!

4 个答案:

答案 0 :(得分:4)

如果你想存储许多值,你应该使用数组

$audio[] = "x";
$audio[] = "z";
$audio[] = "r";
$audio[] = "b";
$audio[] = "x";
$audio[] = "z";
$audio[] = "r";
$audio[] = "b";

foreach ($audio as $value) {
  //// do something with $value
}

如果你不能这样做,你必须使用你的$ audioX_1 var名称,你可以做这样的事情

for ($x = 1; $x <= 8; $x++) {
    $varname = "audio{$x}_1";
    $value = $$varname;
}

答案 1 :(得分:0)

只需使用数组。

$audio = array("x", "z", "r", "b", "x", "z", "r", "b");
foreach ($audio as $audioTemp) 
{
  $audioTemp //will be x then z then r and so on
}

答案 2 :(得分:0)

    $audio1_1 = "x";
    $audio2_1 = "z";
    $audio3_1 = "r";
    $audio4_1 = "b";
    $audio5_1 = "x";
    $audio6_1 = "z";
    $audio7_1 = "r";
    $audio8_1 = "b";

    for ($x = 1; $x <= 8; $x++) {
        $varName="audio".$x."_1";
        echo $$varName;
    }

答案 3 :(得分:0)

$audio1_1 = "x";
$audio2_1 = "z";
$audio3_1 = "r";
$audio4_1 = "b";
$audio5_1 = "x";
$audio6_1 = "z";
$audio7_1 = "r";
$audio8_1 = "b";

for ($x = 1; $x <= 8; $x++) {
    $var = "audio".$x."_1";
    print $$var; 
}