php - Why the array_rand() is not returning me the expected array output? -


i've array titled $all_events follows :

array (     [status] => 1     [data] => array         (             [0] => array                 (                     [group_name] =>                      [event_id] => 201                     [view_id] => 0                     [is_featured] => 0                     [is_sponsor] => 0                 )              [1] => array                 (                     [group_name] =>                      [event_id] => 235                     [view_id] => 0                     [is_featured] => 0                     [is_sponsor] => 0                 )              [2] => array                 (                     [group_name] =>                      [event_id] => 236                     [view_id] => 0                     [is_featured] => 0                     [is_sponsor] => 0                                    )          )      [msg] => success ) 

in resultant array want 2 elements inner array['data'] written following code :

$new_arr = array_rand($all_events['data'], 2); print_r($new_arr); die; 

i got following weird output :

array (     [0] => 0     [1] => 2 ) 

the expected result should follows(if first , last elements selected randomly):

array             (                 [0] => array                     (                         [group_name] =>                          [event_id] => 201                         [view_id] => 0                         [is_featured] => 0                         [is_sponsor] => 0                     )                          [2] => array                     (                         [group_name] =>                          [event_id] => 236                         [view_id] => 0                         [is_featured] => 0                         [is_sponsor] => 0                                        ) ) 

why so?

thanks.

you receive array of keys. doc

when picking 1 entry, array_rand() returns key random entry. otherwise, array of keys random entries returned. done random keys can picked array random values. trying pick more elements there in array result in e_warning level error, , null returned.

user code

foreach(array_rand($all_events['data'], 2) $key)     $new_arr[] = $all_events['data'][$key]; print_r($new_arr); 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -