How to echo an array in PHP?
In this tutorial, we are going to see how to echo an array in PHP. Versus to “normal” variables, the values associated with array keys cannot always be output via echo():
Example :
<?php $var = 'January'; $month1 = array('January', 'February', 'March'); $month2 = array('jan'=>'January', 'feb'=>'February', 'ma'=>'March'); $month3 = array( 'start'=>array('January', 'February'), 'end'=>array('November', 'December') ); echo("The first month of the year is $var.\n"); // output: The first month of the year is January. echo("The first month of the year is $month1[0].\n"); // output: (...) January. //echo("The first month of the year is $month2['jan'].\n"); // Fatal Error echo("The first month of the year is $month2[jan].\n"); // no fatal error, although this notation is bad style; output: (...) January. echo("The first month of the year is the $month3[start][0].\n"); // output: (...) Array[0]. // if the array is not embedded in a string, it can be output without issues: echo($month3['start'][0]); // output: January ?>
Output:
The first month of the year is January. The first month of the year is January. The first month of the year is January. The first month of the year is the Array[0]. January[st_adsense]
So when outputting multidimensional arrays, the normal notation causes problems.
This can be resolved in two ways: Either you surround the array at this point in the string with curly braces or you break the string:
<?php $month3 = array( 'start'=>array('January', 'February'), 'end'=>array('November', 'December') ); // With curly braces echo("The first month of the year is {$month3['start'][0]}.\n"); // Break the string or connecting the strings echo("The first month of the year is ".$month3['start'][0]."."); ?>
Output:
The first month of the year is January. The first month of the year is January.
If you use single quotation marks, the notation with curly braces cannot be used, which means only the connection of several strings remains.
<?php $month3 = array( 'start'=>array('January', 'February'), 'end'=>array('November', 'December') ); // With curly brackets echo('The first month of the year is {$month3[start][0]}'); echo("\n"); // Break the string echo('The first month of the year is '.$month3['start'][0].'.'); ?>
Output:
The first month of the year is {$month3[start][0]} The first month of the year is January.[st_adsense]