有没有更简单的方法在字符串中打印PHP数组?

As you know, a good programmer is a lazy programmer, but I'm just lazy. My question is this: Is there a simpler way to print out an element of an array (from a MySQL query) in a PHP echo statement?

I usually do this:

echo "string start " . $array['element'] . " string end";

It works FINE, I'd just like a shorter way of printing it out, because echo sees the "['element']" bit of the variable as a string. I could use list() to get all the elements, but that's not what I'm after.

So, are there any answers out there?

Thanks for reading,

James

As I heavily dislike interpolating variables in strings I prefer using echo with several arguments:

echo 'string start ', $array['element'], ' string end';

Apart from this being faster then string concatenation (.) it deals better with echoing results of expressions, because , has the lowest of all precedences.

Surround your array with {} for string interpolation, or use sprintf

<?php
    $array = array('foo'=>'bar');

    echo "Print it with {}: {$array['foo']}";
    echo "
";
    echo sprintf("Print it with sprintf: %s", $array['foo']);

I'm note sure i understand what you want to do.

If you want a "shorter" version, ommit the concatenation like so:

echo "string start $array[element] string end";

This also works:

echo "string start {$array['element']} string end";

You can actually just do

echo "string start $array[element] string end";

PHP allows vars in double-quoted strings. That being said, please don't.

$s = 'string start ';
$e = ' string end';
$v = $arr['element'];

// Now you need only 14 keystrokes:
echo $s.$v.$e;