0

bit new to PHP I've been playing around a bit with it but I am unsure how to assign the string value of an array to a variable and print it. Currently it is only displaying the array number rather than it's data.

Any help/explanation appreciated

My current code is:

<?php

$family_friends = array();

array_push($family_friends, "James ");
array_push($family_friends, "Patrick");
array_push($family_friends, "Kevin");
array_push($family_friends, "Miles");
array_push($family_friends, "Reuben");

sort($family_friends);


// Randomly select a winner!

$winner = array_rand($family_friends, 1);

// Print the winner's name in ALL CAPS

strtoupper($winner);


echo " ". "Congratulations"." ".($winner) . "!";

?>
4
  • us1.php.net/manual/en/… Commented Feb 6, 2014 at 22:21
  • This question appears to be off-topic because as reading the manual would have provided the answer. Commented Feb 6, 2014 at 22:22
  • @vascowhite - I didn't see that as one of the canned off-topic reasons :-) Commented Feb 6, 2014 at 22:22
  • @SeanBright That's the beauty of 'other'. You can make up your own :) Commented Feb 6, 2014 at 22:23

2 Answers 2

4

array_rand returns a random index, not a random element. You need to index into the array with its return value. You also need to assign the result of strtoupper to a variable. So:

strtoupper($winner);

Becomes:

$winner = strtoupper($family_friends[$winner]);
Sign up to request clarification or add additional context in comments.

Comments

3

array_randreturns an index, not an element. Therefore, you have to select the element of your array at the random index. Like this

strtoupper($family_friends[$winner]);

If $winner equals zero, $family_friends[$winner] equals "James".

1 Comment

Thanks for the help believe I understand this properly now had not realized it returned the index value, much appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.