0

I've tried to use an array in a loop (in PHP) so that I can display 5 random values. But the problem is that the program doesn't work and nothing appears on the browser.

What's wrong with this code? Have I missed something?

<?php

$my_array = array('Mohammed', 'Khaled', 'Nasser', 'Yasser', 'Ahmed', 'Badr', 'Ibrahim', 'Ali', 'Turkey', 'Abdullah', 'Bandar', 'Omar', 'Saleh', 'Saeed', 'Salem');
$random_array = array_rand($my_array, 5);

for ($x==0 ; $x==4 ; $x++) {
    echo $my_array[$random_array[$x]] . "</br>";
}

?>
1
  • 2
    $x == 0 is a comparison, you want an assignment $x = 0, the loop condition should be a comparison $x < 5 Commented Jun 2, 2015 at 10:13

3 Answers 3

2

Update your for loop as

for ($x=0 ; $x<=4 ; $x++) {
    echo $my_array[$random_array[$x]] . "</br>";
}

You need to learn how for loop works

1. $x=0;//Initializing value of $x 
 2. $x<=4;//Loop till the value of $x is less than or equal to 4 
 3. $x++;//Increment the value of $x by one i.e. $x= $x+1
Sign up to request clarification or add additional context in comments.

Comments

0

You could do it more simple. Also == is for comparison not assignment.

foreach(array_rand($my_array, 5) as $item) {
    echo $item . '<br>';
}

Comments

0
This will work 

<?php

$my_array = array('Mohammed', 'Khaled', 'Nasser', 'Yasser', 'Ahmed', 'Badr',   'Ibrahim', 'Ali', 'Turkey', 'Abdullah', 'Bandar', 'Omar', 'Saleh', 'Saeed', 'Salem');
$random_array = array_rand($my_array, 5);

for ($x=0 ; $x<6 ; $x++) {
echo $my_array[$random_array[$x]] . "</br>";
}

?>

1 Comment

$x < 6 should be $x < 5

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.