Show What You Know!


#1

Show What You Know!

My code works. I just don't understand how it produces a random name from the array.
I know these lines help me do it:

    $item = count($myFamily);
    $win = $myFamily[rand(0, $item -1)];
    print strtoupper($win);

The first line is counting the # of elements in the array and the last one prints the random win.
The second one does the work but I don't understand how. How does it randomly select a name?

<html>
    <p>
	<?php
	// Create an array and push on the names
    // of your closest family and friends
    $myFamily = array();
    array_push($myFamily, "Shajia Abidi");
    array_push($myFamily, "Ghazanfar");
    array_push($myFamily, "Raza");
    array_push($myFamily, "Abidi");
    array_push($myFamily, "Hani");
    array_push($myFamily, "Kulsoom");
	// Sort the list
        sort($myFamily);
	// Randomly select a winner!
        $item = count($myFamily);
        $win = $myFamily[rand(0, $item -1)];
        print strtoupper($win);
     
        

	?>
	</p>
</html>


#2

rand() works like this:

rand(min, max) means pick a random number between, and including, min and max.

In your code, min is always 0 and max is the number of items in your myFamily array minus 1.

So that will be rand(0, 5) -- so your random number result could be anything from 0 to 5.

That random number is used to pick a name from your myFamily array, for example: $myFamily[2]


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.