Can this be done in 1 line with PHP?
Would be awesome if it could:
$out = array("foo","bar");
echo $out[0];
Something such as:
echo array("foo","bar")[0];
Unfortunately that's not possible. Would it be possible like this?
So I can do this for example in 1 line:
echo array(rand(1,100), rand(1000,2000))[rand(0,1)];
So let's say I have this code:
switch($r){
case 1: $ext = "com"; break;
case 2: $ext = "nl"; break;
case 3: $ext = "co.uk"; break;
case 4: $ext = "de"; break;
case 5: $ext = "fr"; break;
}
That would be much more simplified to do it like this:
$ext = array("com","nl","co.uk","de","fr")[rand(1,5)];
Why not check out the array functions on the PHP site?
Well, if you're picking a random element from the array, you can use array_rand()
.
$ext = array_rand(array_flip(array("com","nl","co.uk","de","fr")));
echo array_rand(array_flip(array('foo', 'bar')));
array flip takes an array and swaps the keys with the values and vice versa. array_rand pulls a random element from that array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With