better solution?

1.7k Views Asked by At

This script picks element inside of the array and print it.

<?php
    $word = array("THE", "QUICK", "BROWN", "FOX", "JUMPS");
    $rand_keys = array_rand($word, 2);
    echo $word[$rand_keys[0]];
    echo $word[$rand_keys[1]];
?>

it works but i'm using some function

array_diff();

which on my script search from the $word variable and removes from the element list example:

$word = array("THE", "QUICK", "BROWN", "FOX", "JUMPS");

$sentence = array("QUICK", "BROWN");

$input = array_diff($word, $sentence);

so $input is containing array("THE", "FOX", "JUMPS"); right?

and I apply to the script like to this:

<?php
    $word = array("THE", "QUICK", "BROWN", "FOX", "JUMPS");
    $sentence = array("QUICK", "BROWN");
    $input = array_diff($word, $sentence);
    $rand_keys = array_rand($input, 2);
    echo $input[$rand_keys[0]];
    echo $input[$rand_keys[1]];
?>

it also works because it contains 3 elements on the array. If I do more filtering and the

$input

variable contains only 1 element ex: $input only contains array("BROWN"); the script won't run anymore and getting errors like:

Warning: array_rand(): Second argument has to be between 1 and the number of elements in the array in

Notice: Undefined index: in

Notice: Undefined index: in

how can I run the script if the array element containing only 1?

I've come this far it works but is there any better solution?

<?php
$word = array("THE", "QUICK", "BROWN", "FOX", "JUMPS");

if(count($input) >= 2)
{
    $rand_keys = array_rand($input, 2);
    echo $input[$rand_keys[0]] . "\n";
    echo $input[$rand_keys[1]] . "\n";
}
else
{
    echo end($input);
}
?>
1

There are 1 best solutions below

3
Elon Than On

Error message is simple and easy to understand. You can't use number bigger than count of elements in second argument of array_rand().

Before calling this function check what is count of elements and in case it's only one, use this element without calling array_rand(). Also be prepared for situation when you've got no elements at all.