php - Changing Wordpress function
one text
Solution:
Using array_rand
You could use array_rand
in php to select a random element from an array, here is the official documentation from php.net
and your code will be something like:
for($i=0 ; $i<5 ; $i++){
$term_list .= $terms [array_rand($terms )] . ', ';
}
$term_list = rtrim($term_list, ', ');
// replace the last comma with 'and'
$portion = strrchr($term_list , ',');
$term_list = str_replace($portion, (" and" . substr($portion, 1, -1)), $term_list );
Using shuffle and array_slice
Another solution to pick up random elements from an array could be using shuffle
to randomly shuffle the elements of an array and then using array_slice
to pick up certain elements.
Here is an example of code:
shuffle($terms );
print_r(array_slice($terms , 0, 3));
Source