Jump to content

Random Outcome.


Kristian_C
 Share

Recommended Posts

There are a few things wrong. First, you should refer to something inside an array (such as $_POST) in quotes. If you leave out the quotes, the parser assumes you are trying to use a defined constant. Other then that, see what I did and maybe you can see what you did wrong:

if ($_POST['test']){$nr=rand(0,2);$test = array('Hello','Hey','Test');echo $test[$nr];

Also, since there are three elements in the array, the random number should go from 0 to 2, not 0 to 3. The three array elements are 0, 1, and 2. 3 is not in there.

Link to comment
Share on other sites

Aha, i think i can see what i did wrong :).. dident add the "select random" or what i can name it.. like $test[$nr]. the : [] counts the random tight? or not counts but selects or something? hehe..
You can think of an array in PHP as a list. The array you created here is a list with 3 items in it, the items are the strings "Hello", "Hey", and "Test". Items in an array are also referred to as elements. Each element has an index or key that you can use to refer to it. If "Hello" is the first element in the array $test, then you can refer to it with $test[0]. If "Test" is the third element, then you can refer to it as $test[2]. Arrays are zero-based, meaning that the first element is element 0, not element 1. So, an array with n elements will be numbered 0 to n-1. An array with 10 elements will have keys 0-9.There are also associative arrays, which are arrays that have names for indexes instead of numbers. So you can create an array like this:$person = array("name" => "Steve", "age" => 27, "state" => "dazed");And you can refer to those elements as $person['name'], $person['age'], etc.If you want to get a random element from an array, you can use this function:http://www.php.net/manual/en/function.array-rand.php$random_array_element = array_rand($test_array);
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...