简体   繁体   中英

Is it possible to reference a variable before defining it?

A very simplified version of what I am trying to do:

$quote = "Currently showing number $i";

for($i=0;$i<100;$i++){
echo $quote;
}

Where the $i from $quote is constantly updated with the new value.

Again this is a simplified example. I realize it could be reordered to accomplish the same thing or a str_replace() used, but for the real code it could not be accomplished.

You could use sprintf() / printf() which would have a placeholder that you can dynamically assign the value of $i to:

$quote = "Currently showing number %u";

for($i=0;$i<100;$i++){
    printf($quote, $i);
}

Demo

I would just do something like:

$quote = "Currently showing number ";

for($i=0;$i<100;$i++){
echo $quote.$i;
}

Here is your answer

<?php

$quote = 'Currently showing number $i';
$pattern = '/\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)/';
preg_match_all($pattern, $quote, $matches);

for ($i=0; $i<100; $i++) {
    foreach ($matches[1] as $index => $valName) {
        if (isset(${$valName})) {
            $result = str_replace($matches[0][$index], ${$valName}, $quote);
        }
    }
    echo $result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM