Aaron Rabinowitz Aaron Rabinowitz - 1 year ago 61
PHP Question

undefined variable variable declaration in PHP and array to string convertion

For some reason I am getting undefined variable and string to array conversion
I don't understand why either of these is happening

Notice: Undefined variable: body in C:\Users\New\Desktop\xampp\htdocs\yakov\sendemail.php</b> on line <b>20

Notice: Array to string conversion in C:\Users\New\Desktop\xampp\htdocs\yakov\sendemail.php on line 33
"Array'services.html: ''services.html'\n\n'new york: ''new york'\n\n'new york: ''new york'\n\n'round_trip: ''round_trip'\n\n'2016-09-16: ''2016-09-16'\n\n'2016-09-23: ''2016-09-23'\n\n'nonstop: ''nonstop'\n\n'flexible: ''flexible'\n\n'Business: ''Business'\n\n'1 Adult: ''1 Adult'\n\n'some: ''some'\n\n'one: ''one'\n\n'someonesemail@gmail.com: ''someonesemail@gmail.com'\n\n'new york: ''new york'\n\n'dsfa\n: ''dsfa\n'\n\n'4127117117: ''4127117117'\n\n'me: ''me'\n\n;"

here is my code that is causing the problem I tried playing around with it

header('Content-type: application/json');
$status = array(
'message'=>'Thank you for contacting us. We will contact you as early as possible.'
//print phpinfo();
ini_set('display_errors', 'On');
$email_to = 'Sales@ElyonTravel.com';
if (!empty($_REQUEST)) {
foreach($_REQUEST as $key => $val) {
if (isset($_REQUEST[$key])) {
$body .= "'". $_REQUEST[$key] .": '" . $val . "\n\n";

$email = isset($_REQUEST['email']) ? trim(stripslashes($_REQUEST['email'])) : "NA";
$subject = isset($_REQUEST['subject']) ? trim(stripslashes($_REQUEST['subject'])) : "NA";
$body .= ";";
$email_from = $email;
//$email_to = 'Sales@Travel.com';// your email
$success = mail($email_to, $subject, $body, 'From: <'.$email_from.'>');

echo json_encode($status .$body);

any other suggestions would be appreciated since I am new to the back end

Answer Source

I'm not sure what you're doing with this:


I see three stray $body;'s in your code. Get those out of there. As mentioned in the comments, just define it once as a string at the top:

$body = "";

Then you can concatenate other strings to it all you wish.

The array to string error is probably due to the fact that you're trying to concatenate a string with an array:

echo json_encode($status .$body); 
// ^-- this won't work. $status is an array. $body is a string.

If you're just echoing out that json for fun, you could always add your body string to that status array and then echo it out:

$status['body'] = $body;
echo json_encode($status);