Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
126 views
in Technique[技术] by (71.8m points)

How to concatenate PHP variable name?

I have a PHP for loop:

for ($counter=0,$counter<=67,$counter++){

echo $counter;
$check="some value";

}

What I am trying to achieve is use the for loop variable and append it to the name of another variable.

Bascially, I want the PHP output to be as follows for each row

1
$check1="some value"

2
$check2="some value"

3
$check3="some value"

4
$check4="some value"

etc etc 

I have tried $check.$counter="some value" but this fails.

How can I achieve this? Am I missing something obvious?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The proper syntax for variable variables is:

${"check" . $counter} = "some value";

However, I highly discourage this. What you're trying to accomplish can most likely be solved more elegantly by using arrays. Example usage:

// Setting values
$check = array();
for ($counter = 0; $counter <= 67; $counter++){
    echo $counter;
    $check[] = "some value";
}

// Iterating through the values
foreach($check as $value) {
    echo $value;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...