I am trying to re-create an array by choosing random elements of an existing array using array_rand().
However, when using the following code and spitting out the array, I am getting an undefined index error in reference to it.
The array is $city_users_trimmed
.
PHP code:
$rand = array_rand($city_users_trimmed, 1);
$data = array($city_users_trimmed[$rand[0]]);
I know that $city_users_trimmed has at least 1 element in it, so there is no reason I see why this wouldn't be working.
I tested it by running:
$data = array($city_users_trimmed[0]);
which works, so there is at least one element in the $city_users_trimmed array. Is there anything you see that is causing this issue? Thank you.
Check http://php.net/manual/en/function.array-rand.php
When picking only one entry, array_rand() returns the key for a random entry. Otherwise, an array of keys for the random entries is returned.
So in $rand is your key, not in $rand[0]
According to the doc
mixed array_rand ( array $array [, int $num = 1 ] ) Picks one or more random entries out of an array, and returns the key (or keys) of the random entries.
as you asked 1 key, $rand is an int
$city_users_trimmed = array(1,2,3,4,5,6,6,7,8,8,9,90,8,6,5,4,5,76,78,75,643,54,543,53,43,5345,34534,535);
var_dump($city_users_trimmed);
$rand = array_rand($city_users_trimmed, 1);
var_dump($rand);
$data = array($city_users_trimmed[$rand[0]]);
var_dump($data);
this code will give you the Notice Undefined index in line 5 because of "$data = array($city_users_trimmed[$rand[0]]);" you cant treat with an simple variable as an array. so right code will be
$city_users_trimmed = array(1,2,3,4,5,6,6,7,8,8,9,90,8,6,5,4,5,76,78,75,643,54,543,53,43,5345,34534,535);
var_dump($city_users_trimmed);
$rand = array_rand($city_users_trimmed, 1);
var_dump($rand);
$data = array($city_users_trimmed[$rand]);
var_dump($data);