Kynikos
Kynikos

Reputation: 69

PHP: concatenation of multidimensional array elements

I want to concatenate one element of a multidimensional array with some strings.

<?
$string1 = 'dog';
$string2 = array
           (
            'farm' => array('big'=>'cow', 'small'=>'duck'),
            'jungle' => array('big'=>'bear', 'small'=>'fox')
           );
$string3 = 'cat';
$type = 'farm';
$size = 'big';
$string = "$string1 $string2[$type][$size] $string3";
echo($string);
?>

By using this syntax for $string, I get:

dog Array[big] cat

I would like not to use the alternate syntax

$string = $string1 . ' ' . $string2[$type][$size] . ' ' . $string3;

which works.

What's wrong with "$string1 $string2[$type][$size] $string3"?

Upvotes: 2

Views: 1860

Answers (3)

UltraInstinct
UltraInstinct

Reputation: 44444

Use this:

$string = "$string1 {$string2[$type][$size]} $string3";

Upvotes: 0

Stephen
Stephen

Reputation: 18964

I'm not a fan of complex syntax, or variable parsing in strings. Normally I would use the "alternate" syntax you described. You could do this as well:

$string = implode(' ', array($string1, $string2[$type][$size], $string3));

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816472

Use the "complex syntax":

$string = "$string1 {$string2[$type][$size]} $string3";

PHP's variable parsing is quite simple. It will recognize one level array access, but not more level. By enclosing the expression in {} you explicitly state which part of the string is a variable.

See PHP - Variable parsing.

Upvotes: 6

Related Questions