0

I'm new to PHP (coming from ASPNET) and I'm having a bit of trouble understanding why this isn't working. I'd like to shuffle an array (of custom Quote objects) but when I call the shuffle() function it seems to simply return an integer value (presumably a random number).

According to the manual I should be able to call shuffle and pass in my array: http://php.net/manual/en/function.shuffle.php

/**
* @public
* Retrieves a collection of Quote objects from the datasource
* @param string $author An optional author to filter on
* @return array 
*/
public function GetRandom($author='') {
  //ToDo: Work out correct way to randomize array!
  //return shuffle($this->GetAllQuotes($author));

  // This is my lame temporary work-around until I work out how to
  // properly randomize the array from $this->GetAllQuotes(string)
  $quotes = $this->GetAllQuotes($author);
  $rand_item = shuffle($quotes);
  $rand_arr[] = $quotes[$rand_item];
  return $rand_arr;
}

/**
* @protected
* Retrieves a collection of Quote objects from the datasource
* @param string $author An optional author to filter on
* @return array 
*/
protected function GetAllQuotes($author='') {
  // This code builds Quotes array from XML datasource
}

I'd really like the GetRandom function to return a randomized array of Quote objects rather than just a single one but the shuffle() feature doesn't seem to work as advertised, at least not if the array is populated with custom objects.

2
  • 3
    shuffle() returns a bool for success / failure. It randomises the actual array you've passed in. Commented Sep 1, 2015 at 14:15
  • 3
    shuffle() passes value by reference, no need to assign it to variable. Commented Sep 1, 2015 at 14:16

1 Answer 1

2

Shuffle takes an array by reference, so you can't use it inline in a return statement. Most array sorting functions in php are by reference.

Solution:

public function GetRandom($author='') {
  $quotes = $this->getAllQuotes($author);
  shuffle($quotes); 
  return $quotes;
}
Sign up to request clarification or add additional context in comments.

1 Comment

@NealBailey Don't feel foolish. I've asked much much more ignorant questions. My only advice is to "remember the manual" and keep it holy --> php.net

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.