[proposal + patch] array_pick() function

From: Date: Mon, 23 Jul 2012 00:15:10 +0000
Subject: [proposal + patch] array_pick() function
Groups: php.internals 
Request: Send a blank email to internals+get-61632@lists.php.net to get a copy of this message
Hi there, This is a small function, called array_pick(), which takes one argument ($array), an array, and returns the value of a random item. Much of its usefulness stems from the new short array syntax, which lets you do array_pick(["funlogo.png", "coollogo.jpg", "kittens.gif"]);, instead of $a = array("funlogo.png", "coollogo.jpg", "kittens.gif"); $a = $a[array_rand($a)]; It's also useful for picking a random value out of a none-literal array. For instance today it would have been handy for my markov chain propaganda generator (not the most practical example, I realise.) However, of course, PHP already has array_rand(), and an equivalent function could be implemented in 3 lines of code. The reason I'd like it added to PHP though is largely convenience. It's in at least two other languages I use (Python's random.choice(), Game Maker/GML's choose()) and I use it quite often in different projects (just today I've needed it 4 times in PHP code). It's also the logical counterpart to array_rand(), which gets a random key, not a random value, so it would help API completeness. I'm pretty sure I'm not the only person who wants to fetch a random array value, not a random array key, too. It's useful also in the scenario where you want a random value of nested arrays ($array['thing']['foo']). Enough rambling, here's a pull request. https://github.com/php/php-src/pull/142 <https://github.com/php/php-src/pull/142> -- Andrew Faulds http://ajf.me/

« previous php.internals (#61632) next »