phpvariables

Can a variable embedded in string be changed after the string is declared?


Not sure of a better title for this question but basically heres my code:

<?php

$v = file_get_contents('http://examplecom/index.php?=');

$popularnames = array('Gravity Falls','The Amazing World of Gumball','South Park','American Dad');

?>

Basically what im trying to do is reference the $popularnames array in different areas so like in my href for example this is what i need:

<a href="<?= $v.urlencode($popularnames[0]); ?>"><?= $popularnames[0]; ?></a>

Basically what it should be doing is adding popularnames[0] (Gravity Falls) url encoded to the file_get_contents url of $v but for some reason all it does is output Gravity Falls

But my result should have gotten me http://example.com/index.php?=Gravity+Falls and then have do file_put_contents to it and its result should then have been Hello World! or whatever the page was displaying.

I cant just add $popularname[0] to the $v as im using the $v in multiple href's so doing that it will make all the hrefs one url but I want them different like:

<a href="<?= $v.urlencode($popularnames[0]); ?>"><?= $popularnames[0]; ?></a>

<a href="<?= $v.urlencode($popularnames[0]); ?>"><?= $popularnames[1]; ?></a>

<a href="<?= $v.urlencode($popularnames[0]); ?>"><?= $popularnames[2]; ?></a>

Using this works fine doe so theres no issue with what the variable contain:

<?php $v = file_get_contents('http://example.com/index.php?q='.urlencode($popularnames[0])); echo $v; ?>

Any ideas?

From an answer below how can I make it more compact so it would preferably make me able to just do <?= $v.$v2.$popularnames[0]; ?>:

<?php
$v = 'http://example.com/index.php?q=';
$v2 = file_get_contents($v.urlencode($popularnames[0])); echo $v2;
?>

Do note that the echoed $v2 will be echoed inside a src=" "


Solution

  • But my result should have gotten me http://example.com/index.php?=Gravity+Falls

    Then just store the URL fragment in $v:

    $v = 'http://examplecom/index.php?=';
    

    Currently you're getting the file contents of that URL fragment and storing that in $v:

    $v = file_get_contents('http://examplecom/index.php?=');
    

    If the contents of that incomplete URL are empty, then naturally $v would be empty. And concatenating an empty string with another string would result in just that other string.

    (Side note: I'm not sure what you plan to do at index.php since the query string value you're sending doesn't have a key associated with it. Maybe you forgot to include the key in the URL fragment?)