This forum is now read-only. Please use our new forums at discuss.codecademy.com.

Functions, Part I Forum

View Course » View Exercise

540 points
F537191aa008a2175892888b03a46ed5?s=140&d=retro
Submitted by
Joel.Macke
about 2 years ago

I've passed technically but testing the code proves something is wrong

I've technically passed as in my code works. But I kept noticing that the same name would pop up as the "winner" I tested it by replacing the name and the name would switch to the top name. I'm thinking something happens when I sort it and then randomize it. Would it change if I increased the number of people?

<?php
// Create an array and push on the names
// of your closest family and friends
$lottery = array();
arraypush($lottery, "Joel");
array
push($lottery, "Tara");
arraypush($lottery, "Lois");
array
push($lottery, "Jim");
// Sort the list
$lotteryS = sort($lottery);
// Randomly select a winner!
$lotteryW = rand(0,count($lotteryS));
// Print the winner's name in ALL CAPS
print strtoupper($lottery[$lotteryW]);
?>

I'm not sure if it's the sort or the rand part that's doing this. What are your thoughts?


2 votes

permalink

hi joel-

your issue is coming from this line:
$lotteryS = sort($lottery);

the sort() function does not return the sorted array, it sorts the one you pass it; it returns 1. this means that your count($lotteryS) is always returning 1 and giving you the same winner each time.

take out $lotteryS = and just leave sort($lottery);, replace $lotteryS in your count() call and see what happens!

324 points
Picture
Submitted by
David Fudge
about 2 years ago

1 Comment

F537191aa008a2175892888b03a46ed5?s=140&d=retro Joel.Macke about 2 years ago

Hi David,

Thanks for responding. If I understand you correctly, by putting $lotteryS=sort($lottery); it will always return the first input of the sorted array. But, if I just have sort($lottery); it passes $lottery, which has been sorted, right into rand(0,count($lottery));. This allows it to be sorted differently with each submission. Please let me know if I'm understanding you correctly. Thanks again for your help.


-3 votes

permalink

you need an _ between all the arraypush, should be array_push.

436 points
D532614f047ece8d1a905a5125aa48c3?s=140&d=retro
Submitted by
jaredbenskins
about 2 years ago

1 Comment

5674c6dae39efec455000434_879409444 Zeke Y about 2 years ago

That's Markdown removing the underscore. He actually does have an underscore there.