问题描述:

This question is concerning the final state of variable $message_to_user

Consider the following simplified function:

function myArrayFunction()

{

$message_to_user = array();

$message_to_user[] = array('A Success Message', true);

$message_to_user[] = array('An Error Message', false);

echo $message_to_user;

return $message_to_user;

}

Notice that I echo the array before returning it for troubleshooting and always get Array as the output.

Question

Why isn't the array getting appended with this syntax?

Thank you in advance for your time.

网友答案:

It is, you can't just echo an array like that. It will simply tell you "Hey bud, I'm an array."

Try using var_dump($message_to_user) or print_r($message_to_user)

网友答案:

You can't echo an array, use print_r();

function myArrayFunction()
{
    $message_to_user = array();

    $message_to_user[] = array('A Success Message', true);
    $message_to_user[] = array('An Error Message', false);

    print_r($message_to_user);
    return $message_to_user;
}
网友答案:

The echo expects a string, as the documentation states.

void echo ( string $arg1 [, string $... ] )

Sidenote: echo is not a function anymore. Read the docs linked above.

Arrays are not normal strings to be outputed. They are a collection of data and, for such objective, you need a proper function. PHP offers mainly the print_r() or the var_dump(), beeing the first one more human friendly and the secound able to show the data-type and length of each minimal part of the structure.

In PHP's documentation, you will offen find codes like this:

<pre>
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
</pre>

Just as another side note: that <pre> tag preserves the identation and line-breaking of the text, that is not considered by html when showing things. If you are as impatient as I am, you will also see such identation in the generated source-code as the browsers show them.

网友答案:

N.B.: I'm not looking to overstep RUJordan's accepted answer or anyone else's.

Whether this will help and can prove to be helpful/useful, am only providing as an alternate answer and are welcome to use it.

The following will print:

0 => A Success Message
1 => An Error Message
2 => A Different Message
A Success Message
An Error Message
A Different Message

<?php
$myArray = array();
$myArray[0] = "A Success Message";
$myArray[1] = "An Error Message";
$myArray[2] = "A Different Message";

 foreach($myArray as $key => $value){
    echo $key . " => " . $value . "<br />";
}

echo $myArray[0];
echo "<br>";
echo $myArray[1];
echo "<br>";
echo $myArray[2];

Whilst the following will produce the same result, minus the array keys:

A Success Message
An Error Message
A Different Message

<?php
$myArray = array();
$myArray[0] = "A Success Message";
$myArray[1] = "An Error Message";
$myArray[2] = "A Different Message";

foreach($myArray as $value){
    echo $value . "<br />";
}
相关阅读:
Top