Jump to content

displaying both elements of a randomly picked associative array


AdRock

Recommended Posts

I have a huge array of towns with their counties and I want to pick a town at random and display both the town name and the county they belong in

 

I am having trouble picking a random array element.

 

This is a small part of my array

$towns = array(
'Bedfordshire'=>'Bedford',
'Bedfordshire'=>'Luton',
'Bedfordshire'=>'Dunstable',
'Bedfordshire'=>'Leighton Buzzard',
'Bedfordshire'=>'Biggleswade',
'Bedfordshire'=>'Sandy',
'Berkshire'=>'Reading',
'Berkshire'=>'Bracknell' ,'Maidenhead' ,
'Berkshire'=>'Newbury' ,
'Berkshire'=>'Windsor' ,
'Berkshire'=>'Wokingham' ,
'Berkshire'=>'Abingdon',
'Buckinghamshire'=>'Aylesbury' ,
'Buckinghamshire'=>'Milton Keynes',
'Buckinghamshire'=>'Slough' ,
'Buckinghamshire'=>'Buckingham',
'Buckinghamshire'=>'High Wycombe',
'Cambridgeshire'=>'Cambridge',
'Cambridgeshire'=>'Wisbech',
'Cambridgeshire'=>'Ely',
'Cambridgeshire'=>'March',
'Cambridgeshire'=>'Whittlesey',
'Cambridgeshire'=>'Chatteris',
'Cambridgeshire'=>'Linton'
);

 

What i want to do is pick 120 random towns with their counties out of a possible 248 towns

 

for($i=0; $i < 120; $i++) {
$rand_town = array_rand($towns, 248);

echo $rand_town."<br>"; 
}

 

I've checked the array size and it says its 40 which could be the number of counties in the array.

 

Anyway how can i make sure it picksany of the towns that belongs to a county?

Sorry, I didn't read correctly.

 

This should be what you're looking for, however your array has duplicate array keys, so it will only return the first occurrence.

 

<?php 
$fruit = array("Apple" => "Apple", "Orange" => "Orange", "Banana" => "Banana", "Kiwi" => "Kiwi", "Mango" => "Mango");
$rand_key = array_rand($fruit, 3);

if (is_array($rand_key)) {
  foreach ($rand_key as $key) {
    echo $key .' - '. $fruit[$key] . '<br />';
  }
}
else {
  echo $rand_key .' - '. $fruit[$rand_key];
}
?>

foreach (array_rand($towns, 120) as $key) {
    print $towns[$key];
}

 

That is exacltly what I was trying to do but how do i get it so it goes through a loop a set number of times and pick a random town?

 

I put it in a for loop of 120 and I got over 3000 results where i only need 120 random towns

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.