0

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?

5
  • 3
    Why not just use implode()? Commented Jan 25, 2018 at 22:04
  • Because I need the order of the values to be random, I'm trying to learn how to initialize a string with array values. Commented Jan 25, 2018 at 22:07
  • This would read better without chance for php getting confused: $str = $input[$rand_keys[0]] .', '. $input[$rand_keys[1]]; ... but for that, I'd definitely do what @JayBlanchard asked, and use implode. Commented Jan 25, 2018 at 22:08
  • $str = "{$input[$rand_keys[0]]}, {$input[$rand_keys[1]]}"; should work. But +4 on an implode implementation. Much more readable. Commented Jan 25, 2018 at 22:09
  • @jh1711 Please post your comment as an answer so I can accept. It was just what I was looking for. Commented Jan 25, 2018 at 22:15

2 Answers 2

3

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));
Sign up to request clarification or add additional context in comments.

1 Comment

Personally I hate curly brace hell inside double quotes. But thats my preference, and entirely an opinionated viewpoint. YMMV.
1

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.

1 Comment

Thank you. This was just the answer I was looking for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.