Skip to content Skip to sidebar Skip to footer

How To Echo An Array

It's not like I've never done it before, but for some reason it won't work this time... I'm just returnin an array from a function //Call Function to create the result array $specs

Solution 1:

Print all values of an array

<?phpecho'<pre>';
   print_r($specs);
   // OR var_dump to get variable type (string / int / etc)
   var_dump($specs);
   echo'</pre>';
?>

The echo of the pre tags are for formatting reasons in HTML since the pre tag will show linebreaks (\n) as a visible new line inside of HTML.

As for echoing a single value from an array, all you have to do is refernce the key like you were doing.

echo$specs['length'];

You can make sure the key exists by using the function isset.

if(isset($specs['length'])) {
   echo$specs['length'];
}else{
   echo'Error, Length not found';
}

The functions used in this answer can be found on the PHP.net website var_dump(), print_r() and isset()

Solution 2:

not sure if you want the number of elements of the array :

echo count($specs);

or iterate over your array :

foreach($specsas$key => $value){
    echo"$key : $value<br/>";
}

Post a Comment for "How To Echo An Array"