GTS Joe
GTS Joe

Reputation: 4142

Creating a String from an Array in PHP

I'm trying to create a string out of several array values like so:

$input = array("1140", "1141", "1142", "1144", "1143", "1102");
$rand_keys = array_rand($input, 2);
$str = "$input[$rand_keys[0]], $input[$rand_keys[1]]";

However, in the third line, I get this error: Unexpected '[' expecting ']'

I thought that by converting the array to a value I would be able to use it in my string. What am I doing wrong with my syntax?

Upvotes: 0

Views: 61

Answers (2)

jh1711
jh1711

Reputation: 2328

When you want to expand more than simple variables inside strings you need to use complex (curly syntax). Link to manual. You need to scroll down a little in the manual. Your last line of code will look like this:

$str = "{$input[$rand_keys[0]]}, {$input[$rand_keys[1]]}";

But you could also use implode to achieve the same result.

$str = implode(', ', [$rand_keys[0], $rand_keys[1]]);

It's up to you.

Upvotes: 1

IncredibleHat
IncredibleHat

Reputation: 4104

If you just want to fix your code, simply adjust that one line to this line:

$str = $input[$rand_keys[0]] .', '. $input[$rand_keys[1]];

Here are a couple of other nicer solutions:

shuffle($input);
$str = $input[0] .', '. $input[1];

Or:

shuffle($input);
$str = implode(', ',array_slice($input,0,2));

Upvotes: 3

Related Questions