Undefined Index using array_rand PHP - php

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);

Related

PHP getting random from array return null sometimes

in one array in php i have only one index and data into that, for example:
array:1 [
0 => "{"pk":"4760991153","username":".....","full_name":".....","is_private":true}"
]
in this array i don't know how many data stored into that and when i try to get random index from to access to this index of array i get null sometimes, for example:
$userPages[]=[
'{"pk":"4760991153","username":".....","full_name":".....","is_private":true}'
];
$data = $userPages[rand(0, count($userPages) - 1)
echo json_decode($data)->pk;
or
$randomSelectedTag = array_rand($userPages);
$data = $userPages[$randomSelectedTag];
echo json_decode($data)->pk;
output:
"4760991153",
"4760991153",
"4760991153",
null
"4760991153",
null
how can i fix this problem to make sure getting random from the array don't return null?
If your items have missing keys, don't use rand(0, count($userPages) - 1) as it counts how many items are in the array and returns a random 0-n, not the actual key.
So use array_rand($userPages)
<?php
$userPages=[
0 => '{"pk":"1","username":".....","full_name":".....","is_private":true}',
8 => '{"pk":"2","username":".....","full_name":".....","is_private":true}',
12 => '{"pk":"3","username":".....","full_name":".....","is_private":true}',
64 => '{"pk":"4","username":".....","full_name":".....","is_private":true}'
];
for ($i=0; $i < 10; $i++) {
$data = $userPages[array_rand($userPages)];
echo json_decode($data)->pk.PHP_EOL;
}
https://3v4l.org/JcQea
Or reset the keys, with array_values() then your other method would work.
https://3v4l.org/2HWcG
There is not an issue in the random index, since every random index is from existing array range $data = $userPages[rand(0, count($userPages) - 1).
Reason that causes null results is because you don't check if pk property exists in object, or is it not null. So you should do just simple check:
$randomSelectedTag = array_rand($userPages);
$data = $userPages[$randomSelectedTag];
if(isset($data->pk) && !is_null($data->pk)){
echo json_decode($data)->pk;
}

Does array element has a key

How can I tell if array element, in foreach loop, has a key?
Some code:
function test($p_arr){
foreach ($p_arr as $key => $value){
// detect here if key 'came with the array' or not
}
}
$arr1['a'] = 10;
$arr2[] = 10;
$arr3[2] = 10;
test($arr1); // yes
test($arr2); // no
test($arr3); // yes
edit #1
I am aware that $arr2 also as an automated index-key. I need to know if it is automated or not.
edit #2
My use of it is simple.
In the function, I create a new array and use the $key as the new $key, if it was provided by the function call. or the $value as the new $key, if it was omitted in the function call.
I know that I can just force the use of key to each element, but in some parts of the code, the data structure itself is very dynamic* - and i'm trying to stay flexible as much as possible.
*code that create other code, that create ... and so on.
There is no difference between explicit keys and implicit keys generated via []. The [] doesn't mean "give this element no key", it means "use the next key for this element".
Every element has a key
$arr1['a'] = 10; // key is the string 'a'
$arr2[] = 10; // key is will be the integer zero
$arr3[2] = 10; // key is the integer 2
Edit
Perhaps it would be good to understand why you wish to know if the index is automated or not? It seems odd.
Every array created has to have a key, whether it's a integer or string as the key or index, without no index the PHP would have no way to interpret or even pull information from the array it's self.
$Var = array ("String","anotherstring","sdfhs","dlj");
the above array will automatically be generated with a numeric index starting from 0.
$Array = array();
$Array[] = "This is a string";
The above will push information into the array, as there has been no index or key specified. It will automatically be assigned with the closest numeric value to 0, which does not already exist in the array.
$Array = array();
$Array['key'] = "This is another string";
The above will push information into the array also, but as we have specified an index with a string representation rather an automatically assigned value.
So the answer to your question, if i'm reading this Correctly.
If your referring to check if the array values are specified by PHP/The Code prior to reading the array. There is no soundproof method, as everything would need to be assigned to the array before it has data. further more, if your only adding elements to the array with a string key, then yes. It is possible.
If your relying on automatically generated numeric values, or assigning your own numeric values. it's impossible to tell if PHP has assigned this automatically, or you have specified.

PHP array_rand not working properly

My randomize function does not work properly.
I have an array which is getting randomized.
The array contains three values but only two are chosen each time.
$sterren = array("3","4","5");
$sterrenr = array_rand($sterren, 1);
$sterrenf = $sterren[$sterrenr[0]];
echo $sterrenf;
During the loop when outputting echo $sterrenf only the values 3 and 4 appear but no value 5.
Anyone any ideas ?
When the optional $num parameter is set, array_rand() returns $num random keys. In this case, you're setting the second parameter 1, so you'll get a single key. You just need to echo the corresponding array element:
Change:
$sterrenf = $sterren[$sterrenr[0]];
to:
$sterrenf = $sterren[$sterrenr];
Very easy look with:
First to retrieve the three elements point array_rand to (~,3) not to (~,1).
Second to random as you think is by shuffle in php not by array_rand because array_rand will return a random selection but will rearrange them inside it so after it use "shuffle()" on the output of array_rand "result array" like this what i mean:
$sterren = array("3","4","5");
$sterrenr = array_rand($sterren, 3);
shuffle($sterrenr);
$sterrenf = $sterren[$sterrenr[0]];
echo $sterrenf;

Help with getting first value of array in PHP

Stumped by this one:
I have a function that returns an array of folders in a given directory. When I iterate through the array, I can see all the items. However, if I try to print the first item, I get nothing:
function get_folders($dir) {
return array_filter(scandir($dir), function ($item) use ($dir) {
return (is_dir($dir.'/'.$item) && $item != "." && $item != "..") ;
});
}
$folders = get_folders(".");
$first_folder = $folders[0];
echo $first_folder; // returns blank.
Interestingly, if I don't filter out the "." and "..", then $first_folder does print ".". Can anyone explain this?
As noted in the manual: Array keys are preserved when using array_filter().
The keys are preserved from the call to scandir() which will include the . and .. directories, meaning your filtered array will start at 2 or more (whatever the key is for the first directory).
A simple fix would be to wrap the whole thing in array_values() to get the resultant array having keys starting from 0 and incrementing by one.
return array_values(array_filter(...));
If you don't actually care about the keys, then basic array functions could be of use like key or current.
From the array_filter manual:
Iterates over each value in the input array passing them to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.
So, scandir($dir) gets you an array with . at key 0, thus if you later filter . out, there will be nothing at key 0 in the result.
If you want to know what the first key of the resulting array is, try the array_keys function.
EDIT: actually, salathe's suggestion to use array_values is better in your case than getting the keys from array_keys.
can you print the folders and see if there is some key you can get the first folder with as opposed to selecting the index of zero? It seems lke $folders[0] would work unless the entries are stored with a different set of indexes / keys.
Try doing a
print_r($folders)
to see if it outputs your first folder and all other folders as expected with the corresponding indexes you're looking for.
array_filter preserves array keys, so if the first two elements have been removed, then the "new first" element has an index of 2. To convert that into an array indexed starting from 0, use array_values:
return array_values(array_filter(scandir($dir), function ($item) use ($dir) {
...
As others have said, array_filter preserves the keys in the array. Given that initially the item '.' has key 0, the filtered array ends up not having any item with key 0 (you can verify this with print_r($folders). So this line:
$first_folder = $folders[0];
ends up generating an E_NOTICE saying that there is no key 0 in the array (having notices turned on would alert you to the cause of the problem immediately, I highly recommend it) and giving $first_folder the value null.
To get the first value of the filtered array, regardless of key, use reset:
$first_folder = reset($folders);
if($first_folder === false) {
echo 'No folders!';
}
else {
echo 'First folder: '.$first_folder;
}

php array count max value

If I have:
$mainarray = some array of things with some repeated values
$array_counted = array_count_values ($mainarray);
How can I find the maximum value in $array_counted?
(This would be the element that appeared most often in $mainarray I think. Its mostly a syntax issue as I am pretty sure I could loop it, but not sure of the syntax to use)
You can find first max value as
$main_array = array(1,2,3,4,5,6,6,6,6,6,6,6);
$max_val = max($main_array);
for find all of max vals
in php < 5.3
function findmax($val)
{
global $max_val;
return $val == $max_val;
}
$max_values_array = array_filter($main_array,'findmax');
in php >= 5.3
$max_values_array = array_filter($main_array,function($val) use ($max_val) { return $val == $max_val; });
echo count($max_values_array);
var_dump($max_values_array);
You could sort the array and take the first, respectively last item out of it, if you don't want to loop.
Since you associate the count with the values with that:
$array_counted = array_count_values ($mainarray);
You only need to sort it afterwards, and return the first key (which is the most occured element):
arsort($array_counted);
print key($array_counted); // returns first key
ok, the guy whos answer I used has deleted his comment so here is how I did it:
I used arsort($array_counted) to sort the array, while keeping index. rsort alone does not work as the result of array_count_values is an associative array. Thank you all.

Categories