(resending because of broken formatting)

Hi there,

I apologise for my previous email. It was a disorganised mess that didn't really
make the case for that function very well. So here's a proper proposal (perhaps
too proper?).

Introduction ------------

I am proposing a function, named array_pick(), which takes a single (array)
argument, and returns a random value from it.

Implementation --------------

https://github.com/php/php-src/pull/142

Specification -------------

mixed array_pick(array $array);
The function returns the value of one random array element from $array. Should
said array be empty, then it should return NULL.

Rationale ---------

- array_rand exists, however it only gets a random key, not a random value. This
is the logical counterpart for API completeness
- array_pick is more convenient than $a[array_rand($a)], especially for these
cases:
  - short array syntax + array_pick, e.g. some_func(array_pick(['foo.png',
'bar.jpg', 'foobar.gif'])) vs $a = ['foo.png, 'bar.jpg', 'foobar.gif'];
some_func($a[array_rand($a)]);
  - where using long names or nested arrays, e.g.
some_func(array_pick($foo['bar']['foobar']));
- array_pick is less wasteful than shuffling an array and taking the first
element
- $a[array_rand($a)] issuse a NOTICE from an undefined index if the array is
empty, but array_pick() just returns null, which is more convenient
- I need this function myself quite often. It exists in two other languages I
use that I can think of off the top of my head (Python, Game Maker Language)

Objections ----------
- PHP has too many functions
  - Yes, but that doesn't mean we can't add more. Otherwise we can't improve
things and move forward.
- This can be easily implemented in userland code/this is too frivolous to
warrant addition
  - This is true, however similarly to a lot of standard library functionality,
it is used frequently enough that it is silly to have to rewrite it every time
it is needed
  - It is also the logical counterpart to array_rand(). One for a key, one for a
value.
- The name isn't logical
  - Whilst you could argue that array_rand_key is a better name, I have chosen
array_pick because it is shorter, and has a similar name to similar functions in
Python (random.choice) and GML (choose)
  - However, this could be changed.

---
Thoughts?

--
Andrew Faulds
http://ajf.me/

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to