Nakaro
Nakaro

Reputation: 3

how to access the value of a variable in php

So I have the following:

    $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???
    }

I mean when $x=1 I want to get the value of $audio1_1, when $x=2 I want to get the value of $audio2_1 and so on. Thank you!

Upvotes: 0

Views: 49

Answers (4)

C&#226;rnăciov
C&#226;rnăciov

Reputation: 1144

Just use arrays.

$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
}

Upvotes: 0

Dinesh Patra
Dinesh Patra

Reputation: 1135

$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; 
}

Upvotes: 0

Philipp
Philipp

Reputation: 15629

You shoud use arrays, if you want to store many values

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

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

if you cant do this and you have to use your $audioX_1 var names, you could do something like this

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

Upvotes: 4

Peeje
Peeje

Reputation: 475

    $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;
    }

Upvotes: 0

Related Questions