Re: Variable question

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Sat, 1 Oct 2011, Mike Mackintosh wrote:

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.';');

You could do:

$var = "trivia_answer_.$correct_answer";
echo $$var;

But I agree that an array would be simpler.

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];

You can define this a bit more simply:

$trivia_answer = array (
  1 => 1000,
  2 => 1250,
  3 => 2500,
  4 => 5000
);

You can do it even more simply by just giving the values, but indexes wil start at 0:

<?php
$trivia_answer = array (1000, 1250, 2500, 5000);
print_r ($trivia_answer);
?>

Array
(
    [0] => 1000
    [1] => 1250
    [2] => 2500
    [3] => 5000
)

While manually defining an array like this is only slightly less tedius than using 4 numbered variables, it's a lot easier to do if you're getting data from somewhere else (e.g. a database of trivia questions). To use the original way proposed, you'd have to keep constructing variable names, which arrays avoid quite nicely.

In my opinion, the only real usefulness for a syntax like $$var (above) is if you want to do something with a bunch of variables in one go. For example:

foreach (array ("title", "artist", "album", "label") as $field)
  echo ucwords($field) . ': ' . $$field . '<BR>';

The above comes from a function which manages only a single record, so no real need to use an array. I could of course, e.g. record['title'] etc, but I don't see much could be gained unless I needed to be able to manage an entire record as a single unit.

Geoff.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux