echoing array index and getting a blank page
<?
$array = array('eggs', 'bacon', 'football', 'baseball', 'ford', 'toyota');
$rand_index = mt_rand(0, count($array) / 2 - 1) * 2;
?>
<?php echo "$array[$rand_index]"; ?><?php开发者_开发百科 echo "$array[$rand_index+1]"; ?>
i dunno why this script doesn't work. I want to echo both values but can't
Why don't you just do...
<?
$array = array('eggs', 'bacon', 'football', 'baseball', 'ford', 'toyota');
$rand_index = array_rand($array);
?>
Documentation.
By the way, if you want to do this...
<?php echo "$array[$rand_index]"; ?><?php echo "$array[$rand_index+1]"; ?>
Just introduce the braces around it like so...
<?php echo "{$array[$rand_index]}"; ?>
(it does work when using a PHP variable as an array subscript).
But in that example, it would be better to avoid wrapping with string delimiters. It is confusing and only adds extra overhead.
Try it without the quotes. PHP won't parse the code inside of strings, thankfully :)
echo $array[$rand_index];
Edit: Just wrong, apparently. I didn't realize you could interpolate arithmetic even inside curly brackets. Learn something new every day. Thanks, alex.
$rand_index+1
is creating a syntax error.
try doing:
<?php
$rand_index2 = $rand_index + 1;
echo "$array[$rand_index]";
echo "$array[$rand_index2]";
?>
精彩评论