Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can this be done in 1 line?

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)];
like image 409
Angelo Avatar asked Feb 26 '23 21:02

Angelo


2 Answers

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")));
like image 186
animuson Avatar answered Mar 07 '23 05:03

animuson


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.

like image 40
Jonathan Kuhn Avatar answered Mar 07 '23 06:03

Jonathan Kuhn