After the for-loop, the returned array is wrong
I have something like this:
$n = 2;
$items = array();
$result = array(); // new array with random items
$random_items = array_rand( $items, $n );
for( $f=0; $f<=$n; $f++ ) {
$result[] = $items[$random_items[$f]];
}
$items
looks like
Array ( [0] => file1.jpg [1] => file2.png [2] => file3.jpg ... and so on )
This works fine ... but if I set to , then the script doesn't work or doesn't work correctly! $n
1
If $ n == 2 (or more), the result array has the value of the last element empty
Array ( [0] => 20141125-17826a4b34.png [1] => 20141125-27fe57561d.jpg [2] => )
If $ n == 1 (exactly) the result array is like
Array ( [0] => [1] => )
The result array must be in the same format as the element array, but with $ n random elements.
Thanks in advance!
IN
if( $n > 1 ) {
for( $f=0; $f<$n; $f++ ) {
$result[] = $items[$random_items[$f]];
}
}
elseif( $n == 1 ) {
$result[0] = $items[$random_items];
}
source to share
You should $f < $n
instead$f <= $n
for( $f=0; $f < $n; $f++ ) {
$result[] = $items[$random_items[$f]];
}
Because when you use $f <= $n
it runs to 0,1 (when, $n = 1)
OR 0,1,2 (when $n = 2)
and you are missing the last indexed item.
If only one entry is selected, array_rand () returns the key for the random entry (not array). Otherwise, an array of keys is returned for random entries.
So this means that when you use $n = 1
, then $random_items
is just a value (not an array). eg.
for $n = 1, $random_items = 4;
but for $n >= 2, $random_items = [1, 6, 3, 6];
source to share