2

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"?

2
  • to concatenate strings you should use . sign $string=$string1.$string2[$type][$size].$string3; Commented Feb 3, 2011 at 12:56
  • @fsonmezay, the OP is aware of how concatenation works. Commented Feb 3, 2011 at 12:59

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Felix, Thank you very much for your fast response.
0

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));

1 Comment

Interesting approach to solving the problem.
0

Use this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.