Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert a variable into a PHP array?

I have looked for some responses on the web, 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 in any way?

like image 984
Norm Avatar asked May 03 '12 05:05

Norm


People also ask

Can you put a variable in an array PHP?

Yes, you can store variables within arrays, though you'll need to remove the space between $result and the opening bracket.

How do you add variables to an array?

Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.

How do you create an array of variables in PHP?

To create an array in PHP, we use the array function array( ) . By default, an array of any variable starts with the 0 index. So whenever you want to call the first value of an array you start with 0 then the next is 1 ...and so on. There are different types of arrays in PHP.

Does += work on arrays in PHP?

The + operator in PHP when applied to arrays does the job of array UNION. $arr += array $arr1; effectively finds the union of $arr and $arr1 and assigns the result to $arr .


1 Answers

What you need is (not recommended):

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

or just

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

You've enclosed the variable inside single quotes and inside single quotes variable interpolation does not happen and '$id' is treated as a string of length three where the first character is a dollar.

like image 106
codaddict Avatar answered Oct 08 '22 09:10

codaddict