user3652484
user3652484

Reputation: 3

Why the output is not a string

I tried many time, but I still don't understand why the output is not a string, anything wrong ? help me check it. The final output should be a uppercase name string

<html>
<p>
<?php
// Create an array and push on the names
// of your closest family and friends
$name = array();
array_push($name,"Mike");
array_push($name,"Jane");
array_push($name,"Jack");
array_push($name,"Nike");
array_push($name,"Ash");
array_push($name,"Chris");
array_push($name,"Zark");




// Sort the list
sort($name);
join(",",$name);


// Randomly select a winner!
$random = count($name,rand(0,7));
// Print the winner's name in ALL CAPS
$winner = strtoupper($random);
print($winner);
?>
</p>
</html>

Upvotes: 0

Views: 94

Answers (1)

Brad
Brad

Reputation: 163468

$random = count($name,rand(0,7));

This line assigns the count of elements in $name. I don't know what else you expected to get back other than a number here.

What you really want:

echo strtoupper($name[array_rand($name)]);

http://php.net/manual/en/function.array-rand.php


Other Notes:

  • Your call to join() doesn't do anything useful since you're not doing anything with the return value.
  • Your call to sort is pointless if you're just picking a random entry later.
  • Pick a plural name for your array names so you know they are arrays. $names instead of $name.
  • If you know all of the array elements ahead of time, no need for array_push(), just use an array literal: array('Mike', 'Jane', /* etc */)
  • If you're outputting data into the context of HTML, always use htmlspecialchars() to make sure any reserved characters are escaped properly. This isn't a problem with the code you literally have here, but will be as soon as you want to output < or ".

Upvotes: 11

Related Questions