Home > Back-end >  Get a variable from a concatenated variable PHP and JavaScript
Get a variable from a concatenated variable PHP and JavaScript

Time:09-22

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

<?php
$result = rand(1, 898);

include_once($_SERVER['DOCUMENT_ROOT'].'/016-name.inc.php');

$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" />

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

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

<?php
$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: t

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.

Thanks,

Kaden

CodePudding user response:

Thanks to Tangentially Perpendicular for providing the solution in this comment:

Don't store your names in separately numbers variables. Use an array. Then finding the element you want is trivial. See php.net/manual/en/language.types.array.php

CodePudding user response:

I think you should use the so called variable/dynamic variable :
https://www.php.net/manual/en/language.variables.variable.php using the double dollar sign $$

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

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 
  • Related