开发者

Why does this PHP code just echo "Array"?

开发者 https://www.devze.com 2023-01-09 14:14 出处:网络
Here is my code: if(isset($_POST[\'check\']) AND $_POST[\'c开发者_开发技巧heck\'] == \'First\') {

Here is my code:

if(isset($_POST['check']) AND $_POST['c开发者_开发技巧heck'] == 'First') {
  $errormessage = array();

  if(empty($_POST['full_name']) || strlen($_POST['full_name']) < 4) { 
     $errormessage[] = "FEL - Vänligen ange fullständiga namn. Please enter atleast 3 or more characters for your name";
  }
  if(!isEmail($_POST['usr_email'])) {
     $errormessage[] = "FEL - Invalid email address.";
  }
  if(empty($errormessage)) {
     echo 1;
  } else { 
     echo $errormessage; // <--
  }
}

When echo $errormessage runs it outputs Array. What am I doing wrong?


You are calling echo on an actual array, which does not have an implicit string representation.

In order to output an array's contents you can use the print_r, var_dump or var_export functions or for custom output, you can use array_map or even a foreach loop:

print_r($errormessage);
var_dump($errormessage);
var_export($errormessage);

foreach($errormessage as $error) 
   echo $error . '<br/>';

array_map('echo', $errormessage);


$errormessage is an array and using echo on an array prints just Array.

If you want to print your error messages in a decent way, you can either use foreach to iterate the messages and print each message:

echo '<ul>';
foreach ($errormessage as $message) {
    echo '<li>'.htmlspecialchars($message).'</li>';
}
echo '</ul>';

Or you can even use some advanced array processing like array_map and implode to do something like this that is equivalent to the previously shown when the array contains at least one item:

echo '<ul><li>' . implode('</li><li>', array_map('htmlspecialchars', $errormessage)) . '</li></ul>';


You need to pretty-print the array. How you do this is up to you.

If you're passing the array to some JavaScript, you probably want to encode it as a JSON array:

echo json_encode($errormessage);


$errormessage = array();
$errormessage[] = "...";

Both defines $errormessage as array datatype. Echo prints data from string or numeric format. To print data from array either use print_r as suggested or loop through the members of array and use echo


To see what's inside you variable just do

   print_r( $errormessage );
   // or
   var_dump( $errormessage );


use the code as like this

if(isset($_POST['check']) AND $_POST['check'] == 'First') {
$errormessage = array();
 if(empty($_POST['full_name']) || strlen($_POST['full_name']) < 4)
 {
 $errormessage['error_what_ever_key_you_want'] = "FEL - Vänligen ange fullständiga namn. Please enter atleast 3 or more   characters for your name";
 }
 if(!isEmail($_POST['usr_email'])) {
 $errormessage['error_what_ever_key_you_want'] = "FEL - Invalid email address.";
 }
if(!empty($errormessage)){
echo $errormessage['error_what_ever_key_you_want']; // <--
}
}
0

精彩评论

暂无评论...
验证码 换一张
取 消