How to use echo in php array to return as string

I am trying to return an array of strings. I'm doing it:

$errors[] = toolbarCheckCreds($_COOKIE['uname'], $_COOKIE['pword'], $_COOKIE['rememberMe']);
    echo $errors[0];

      

and this is in the function at the end:

return $errors;

      

and I installed an error like this:

$errors[] = "error goes here!";

      

Basically, when I return my array and echo it, it gives me the following output:

Array

      

+3


source to share


4 answers


You need to iterate over your array. There are several ways to do this, with my personal preference to use a foreach loop .

For example, this will display each error message in the array on a new line:



foreach ($errors as $error)
{
    echo "<br />Error: " . $error;
}

      

+5


source


Use PHP implode to convert your array to a string that you can echo. Using echo on an array will just display the data type.

return implode(' ', $errors);

      

If you want to separate errors with a non-whitespace delimiter, just replace the space in the first parameter:

return implode(' :: ', $errors);

      

For example, if your error array contained three values:



[ "Invalid data" , "404" , "Syntax error" ]

      

then your line, if you used ::, will look like this when you run echo

as a result:

Invalid data :: 404 :: Syntax error

      

See link link included in another example.

+4


source


You cannot display the contents of the array as is.

If you want to check the contents of the array, you can use print_r () or var_export () with the parameter return

set to True

.

+1


source


$ list = array ("One thing", "Two things", "Things");
echo implode (",", $ list);

Result One thing, two things, three things

Easy, breeze, hope this helps, I know I'm late, but might be helpful for someone else, maybe?

0


source







All Articles