Jump to content

Get text from an array


1bigbear

Recommended Posts

I made this:

 

<?php

//my example array
$my_array = ("Orange","Apple","Berry");

//count how many items are in the array
$size_of_array = sizeof($my_array);

//-1 because the index of an array starts at 0.
$size_of_array = $size_of_array - 1;

//number of words you want from the array
$num_words = 3;


if($size_of_array > ($num_words - 1)){
    $num_words = $size_of_array + 1;
}

//an array that will note down what words we have already got
$words_used = array();

//setup loop
$counter = 0;
while($counter < $num_words){
    
    $rand_index = rand(0,$size_of_array); //get a random index
    while(in_array($rand_index,$words_used)){ //make sure word not already used
        $rand_index = rand(0,$size_of_array); //get a random index
    }
    
    echo $my_array[$rand_index];
    array_push($words_used,$rand_index);
    
    $counter++;
}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.