How to insert a variable into a PHP array?

I searched the Internet for answers, but none of them are very accurate.

I want to be able to do this:

$id = "" . $result ["id"] . "";
$info = array('$id','Example');

echo $info[0];

Is this possible anyway?

+5
source share
3 answers

What you need (not recommended):

$info = array("$id",'Example'); // variable interpolation happens in ""

or simply

$info = array($id,'Example'); // directly use the variable, no quotes needed

You included the variable inside single quotes, and inside the single quotes the interpolation variable does not occur, but is '$id'considered as a string of length three, where the first character is the dollar.

+12
source

Just don't put it in quotation marks:

$id = $result["id"];
$info = array($id, 'Example');
echo $info[0];

Alternatively, if you use double quotes rather than single quotes, then it will be interpolated (which also leads to it being converted to a string):

$id = $result["id"];
$info = array("$id", 'Example');
echo $info[0];
+4
source

, , $result .

$foo = $result["bar"]; // assuming value of 'bar'

$collection = array( $foo, "fizz" );

foreach ( $collection as $item ) {
  // bar, fizz
  echo $item;
}
+2

All Articles