Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This code picks 2-6 pitches from the $vec array. I'd like to echo out each individual pitch, but interestingly enough, it gives me the numeric values of the placement of the pitch in the array (ie: 2 5 6 instead of D F F#)

  $pick = rand(2,6);
  $vec = array("C","C#","D","D#","E","F","F#","G","G#","A","A#","B");
  $random_keys = array_rand($vec,$pick);
  foreach ($random_keys as $pitch){
  echo $pitch; echo "<br>";
  }

Why is it doing this and how can I get the pitches instead of the numbers?

share|improve this question
 
This is the documented behavior. See as well the user-notes on the manual page: php.net/array_rand Also take a look what an array is: php.net/array - you can get the values by those numbers (indexes / keys). –  hakre Jun 9 '13 at 7:33
add comment

1 Answer

Try this:

$pick = rand(2,6);
$vec = array("C","C#","D","D#","E","F","F#","G","G#","A","A#","B");
$random_keys = array_rand($vec, $pick);
foreach ($random_keys as $key) {
  echo $vec[$key], '<br />';
}

From array_rand() documentation:

Return value

If you are picking only one entry, array_rand() returns the key for a random entry. Otherwise, it returns an array of keys for the random entries. This is done so that you can pick random keys as well as values out of the array.

share|improve this answer
 
ah that's better. thanks. so as to 'why': array_rand produces a selection of keys rather than the values themselves in the array. (that's why in the manual they called the variable random_keys) correct? –  Gregory Tippett Jun 9 '13 at 5:04
 
@GregoryTippett - :) Yup, the documentation mentions array keys. :D. –  Aiias Jun 9 '13 at 5:06
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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