2
\$\begingroup\$

I am trying to randomly select 4 items out of an array, each item has an index, a name and a price attached to it. Currently I have the following code segment to select 4 at random:

function SelectItems()
{
     $arrayItems = array( 
          1 => "Name of Item 1",
          2 => "Name of Item 2",
          3 => "Name of Item 3",
          4 => "Name of Item 4",
     );

     $arrayItemPrices = array(
          1 => "$6.00",
          2 => "$4.00",
          3 => "$5.00",
          4 => "$15.00",
     );

     $randomKeys = array_rand( $arrayItems, 4 );
     foreach( $randomKeys as $key )
     {
          $name = $arrayItems[$key];
          $price = $arrayItemPrices[$key];

          /* Process item... */
     }
}

However, this is not how I would approach it in C++, I would only use a std::map<int, std::pair<std::string, std::string>>, this would map directly in PHP to an array where the value consisted of a pair of strings, however as there is no pair class in PHP I have done it with two arrays. Is this best practise in PHP?

\$\endgroup\$
3
\$\begingroup\$

I would work with a two dimensional array, in stead of two separate arrays. You could then shuffle your array to get the items in a random order. Something like this:

$items = [
    ['id' => 1, 'name' => 'item 1', 'price' => '$1.00'],
    ['id' => 2, 'name' => 'item 2', 'price' => '$2.00'],
    ['id' => 3, 'name' => 'item 3', 'price' => '$3.00'],
    ['id' => 4, 'name' => 'item 4', 'price' => '$4.00'],
];

shuffle($items);

foreach($items as $item) {
    echo $item['id'] . ': ' . $item['name'] . ' ' . $item['price'];
    // or whatever you want to do, just trying to demonstrate you
    // won't need those $name and $price variables anymore...
}

I find it makes more sense to keep your item's properties together, in stead of spreading them over different arrays. You know when you pick an element from the items array you will have all it's properties. And to me the code is better readable as well.

\$\endgroup\$
  • \$\begingroup\$ Ahh right, that looks much nicer and more legible, especially if I need to add extra properties later; thanks very much! \$\endgroup\$ – Thomas Russell Sep 13 '14 at 13:02
  • \$\begingroup\$ Only one thing, if I have an array with more than 4 items in, I only wish to select 4, how could I do this (array_rand seems to return [1, 2, 3, 4] for some reason)? \$\endgroup\$ – Thomas Russell Sep 13 '14 at 13:08
  • \$\begingroup\$ something like this: $selection = array_slice(shuffle($items), 0, 4); \$\endgroup\$ – Pevara Sep 13 '14 at 14:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.