I've a larger piece of multi-line text that I need to put in an PHP associative array through a here-doc. It looks like this:
$data = [
"x" => "y",
"foo" => "bar",
/* ... other values ... */
"idx" = <<< EOC
data data data data
data data data data
data data data data
EOC;
"z" => 9,
/* ... more values ... */
];
I can't figure out how to put that element "idx" with multi-line text in the $data array through a here-doc.
Associative array will have their index as string so that you can establish a strong association between key and values. The associative arrays have names keys that is assigned to them. $arr = array( "p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110", "t"=>"115"); Above, we can see key and value pairs in the array.
There are three types of an array in PHP. Numeric Arrays, Associative Arrays, and Multidimensional Arrays. An associative array is in the form of key-value pair, where the key is the index of the array and the value is the element of the array. Here the key can be user-defined.
Associative arrays are used to store key value pairs. For example, to store the marks of different subject of a student in an array, a numerically indexed array would not be the best choice.
Heredoc is one of the ways to store or print a block of text in PHP. The data stored in the heredoc variable is more readable and error-free than other variables for using indentation and newline. How the heredoc content can be stored in a variable or printed has shown in this tutorial.
There are several problems, it has to look like this:
$data = [
"x" => "y",
"foo" => "bar",
/* ... other values ... */
// you need to use '=>'
"idx" => <<<EOC
data data data data
data data data data
data data data data
EOC
,"z" => 9, // you can't end it with a semicolon, WHY EVER! and the comma needs to be on a new line
/* ... more values ... */
];
That's some hacky and clunky PHP code. I don't recommend to use it, it's full of problems (maybe caused by the lexer). Better stick to good old strings.
With PHP 7.3 things have improved significantly. You can now do this:
$data = [
"x" => "y",
"foo" => "bar",
/* ... other values ... */
"idx" => <<<EOC
data data data data
data data data data
data data data data
EOC,
"z" => 9,
/* ... more values ... */
];
I had the same problem and I ended up doing this (old solution):
$data = [
"x" => "y",
"foo" => "bar",
/* ... other values ... */
"z" => 9,
/* ... more values ... */
];
$data["idx"] = <<<EOC
data data data data
data data data data
data data data data
EOC;
The idea is that I can use heredoc without extremely ugly array formatting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With