[SOLVED] Get a variable from a concatenated variable PHP and JavaScript


This Content is from Stack Overflow. Question asked by KadenBlox

I’m not sure how to title this post properly… But I hope you can still help!

$result = rand(1, 898);


$con = "number".$result;

<h2>Guess That Pokemon!</h2>
<p>Guess the following Pokemon by it's image only.</p>
<input type="text" placeholder="Guess" style="width:75%;" onkeyup="guess()" id="inputGuess"/>
<img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/home/<?=$result?>.png" />

  function guess(){
    var inputGuess = document.getElementById('inputGuess');
    if (inputGuess.value == '<?=$con?>'){

Inside /016-name.inc.php (shortened for the sake of simplicity, but you can see where I’m going…)

$number1 = "bulbasaur";
$number2 = "ivysaur";
$number3 = "venusaur";
$number4 = "charmander";
$number5 = "charmeleon";
$number6 = "charizard";
$number7 = "squirtle";
$number8 = "wartortle";
$number9 = "blastoise";
$number10 = "caterpie";

What I’m trying to do is get the inputted result in JavaScript, and then try to match the word they enter for the number in the variable.

for example, if the input is Squirtle then I need to try and find the variable of the pokemon number and convert it to the pokemon name to check if it’s correct.

This is what it’s returning:

Expected behaviour:

enter image description here

I’ve had quite a bad history with posts on stack overflow not being specific enough, etc, but I hope this is enough to try and fix my problem.




I think you should use the so called variable/dynamic variable :
using the double dollar sign $$

function guess(){
    var inputGuess = document.getElementById('inputGuess');
    if (inputGuess.value == '<?=$$con?>'){

Let’s put it simply :

$result = rand(1, 898); // let say it worths 421 when the code is run  
$con = "number".$result; // so it will worth "number421"  
$$con will worth $number421 

This Question was asked in StackOverflow by KadenBlox and Answered by Lionel-fr It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?