altonline
altonline

Reputation: 35

PHP - array_rand and if/else statement

I´m not a developer, but i´m trying to make a PHP code that randomly print out ad banners and content widgets in a foreach loop. I have been playing with this code, but it seems like the $random_timeline prints out numbers instead of strings. Any clue why this is happening?

<?php 

$timeline_array = array("none", "none", "ads", "content");
$random_timeline = array_rand($timeline_array, 1);

echo  $random_timeline;
                    if($random_timeline == 'none') {
                    echo $random_timeline;
                    }
                    else if($random_timeline == 'ads') {
                    echo $random_timeline;
                    }
                    else if($random_timeline == 'content') {
                    echo $random_timeline;
                    };
?>

Upvotes: 0

Views: 93

Answers (1)

MrCode
MrCode

Reputation: 64526

array_rand() returns the key not the actual element value, so you can use:

$random_timeline = $timeline_array[array_rand($timeline_array, 1)];

Now, $random_timeline is the element value and your if statements will work.

Upvotes: 1

Related Questions