Re: Variable question

From: Date: Sat, 01 Oct 2011 19:04:20 +0000
Subject: Re: Variable question
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-315105@lists.php.net to get a copy of this message
On 11-10-01 02:03 PM, Mike Mackintosh wrote:
On Oct 1, 2011, at 1:59 PM, Ron Piggott wrote:
If $correct_answer has a value of 3 what is the correct syntax needed to use echo to display the value of $trivia_answer_3? I know this is incorrect, but along the lines of what I am wanting to do: echo $trivia_answer_$correct_answer; $trivia_answer_1 = “1,000”; $trivia_answer_2 = “1,250”; $trivia_answer_3 = “2,500”; $trivia_answer_4 = “5,000”; Ron www.TheVerseOfTheDay.info
Best bet would to toss this into either an object or array for simplification, otherwise that type of syntax would need the use of eval. example: eval('echo $trivia_answer_'.$correct_answer.';'); best bet would be to.. $trivia_answer = array(); $trivia_answer[1] = 1000; $trivia_answer[2] = 1250; $trivia_answer[3] = 2500; $trivia_answer[4] = 5000; echo $trivia_answer[$correct_answer];
Agreed the OP's value list isn't optimal, but eval is not needed to address the solution: <?php
    $trivia_answer_1 = "1,000";
    $trivia_answer_2 = "1,250";
    $trivia_answer_3 = "2,500";
    $trivia_answer_4 = "5,000";
    $answer
        = isset( ${'trivia_answer_'.$correct_answer} )
        ? ${'trivia_answer_'.$correct_answer}
        : 'Not found';
    echo $answer."\n";
?> Cheers, Rob. -- E-Mail Disclaimer: Information contained in this message and any attached documents is considered confidential and legally protected. This message is intended solely for the addressee(s). Disclosure, copying, and distribution are prohibited unless authorized.

« previous php.general (#315105) next »