PHP assiging a variable to an array – PHP

  php

Q(Question):

Do you encapsulate a variable with " " when assigning a variable to an array.

Which of these is correct

$x = array("foo" => ‘"’.$bar.’"’);

or

$x = array("foo" => $bar);

All examples shown are always constants

I would assume option #2 is the correct method.

A(Answer):

This is easy to test. Code both and test the results.

A(Answer):

Yes but I do not have an easy way to display results. Question do you know which is correct?

A(Answer):

Technically the second. The first will work as well as long as the variable is a string.

A(Answer):

The first one is just a string concatenation, so that the value of $bar would be converted into string. Here is the output for $bar=2;


$x => Array (1)
(
| ['foo'] = String(3) ""2""
)
$x => Array (1)
(
| ['foo'] = Integer(1) 2
)

As you see the second one takes the value of $bar as it is. More clearly you can see the difference if $bar is an array like :


$bar = array("drink" => "milk", "desert" => "pudding");

The output is :


$x => Array (1)
(
| ['foo'] = String(7) ""Array""
)
$x => Array (1)
(
| ['foo'] => Array (2)
| (
| | ['drink'] = String(4) "milk"
| | ['desert'] = String(7) "pudding"
| )
)

A(Answer):

Which of these is correct

$x = array("foo" => ‘"’.$bar.’"’);

or

$x = array("foo" => $bar);

both are correct. the difference is that the first one is always a string and that it is 2 chars (preceding and following ") longer.

A(Answer):

Thanks for all the great responses.

LEAVE A COMMENT