0

Trying to get this code to work. It might be easier to show what I'm trying to do, and what is missing:

<?php
    $array=array(
        "something",
        "something else"
    );
    /*pick a random entry in the array and store it as $output*/;
    if(strpos($output,"else") !== false){
        //do stuff;
    }
    echo "<div>";
    echo $output
    echo "</div>"
?>

As you can see, I'm having trouble trying to store a random entry in $output. What I want to do is to pick a random entry from the array, run a strpos on the result to do additional things if the conditions are met, and then output the same random entry between the divs.

EDIT: In case it's not clear, the line commented with /* and */ is supposed to be a 'fill in the blank' line, and not a 'this comment refers to the lines of code below' comment.

2 Answers 2

6

Use array_rand() to get a random entry.

$output = $array[array_rand($array)];
Sign up to request clarification or add additional context in comments.

3 Comments

Wouldn't this result in different random results if $output is called in two different places?
@Hiigaran: Nope. array_rand() will not be called each time you echo it somewhere. Proof: eval.in/136389
I'll give it a try and see how it goes, then.
2

Generate a random number between zero and one less than the length of the array, use that as the array index to get a random item from the array.

<?php
$output = $array[rand(0, count($array)-1];

Comments

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.