开发者

How to shuffle my Array or String list in a more readable way?

Imagine you want to have a very readable, easily editable list of items, separated by comma's only, and then echo 3 random items from that list. Array or string doesnt matter. For now, I got the following working (Thanks webbiedave!)

$fruits = array('Mango', 'Banana', 'Cucumber', 'Pear', 'Peach', 'Coconut');

$keys = array_rand($fruits, 3);   // get 3 random keys from your array
foreach ($keys as $key) {         // cycle through the keys to get the values
    echo $fruits[$key] . "<br/>";
}

Outputs:

Coconut
Pear
Banana

Only thing unsolved here is that the list is not so readable as I wi开发者_高级运维shed: Personally, I very much prefer the input list to be without the quotes e.g. Mango as opposed to 'Mango' , meaning preferably like so:

(Mango, Banana, Cucumber, Pear, Peach, Suthern Melon, Coconut)

Is this easily possible? Thanks very much for your input.


$input = explode(',', 'Mango, Banana, Cucumber, Pear, Peach, Suthern Melon, Coconut');
$input = array_map('trim', $input);


Not without going against PHP standards.

You could define constants such as

define(Mango, "Mango");

and use them in your array, but that would defeat the naming conventions of PHP, as constants should be all UPPERCASE


If you want to have an editable list, I suggest to create a configuration file and read the list from there.

For example, you could use YAML and the symfony YAML parser. Your list would look like this:

- Mango
- Banana
- Cucumber
- Pear
- Peach
- Coconut

This would be a better separation of your code and data. It would also be more maintainable in the long run, as you don't have to touch the actual code when adding or removing elements.

Or of course in your case, you could just have a simple text file with one entry per line and read the file into an array.

If you are worried about performance, you could serialize the generated array to disk or something like that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜