Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use echo in php array to return as a string

Tags:

arrays

php

I am trying to return an array of strings. I do this:

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

and this in the function at the end:

return $errors;

and I set an error like this:

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

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

Array
like image 267
droidus Avatar asked Jul 13 '26 22:07

droidus


1 Answers

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 the errors with a delimiter other than a space, just replace the space in the first parameter:

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

For example, if your errors array contained three values:

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

then your string, if you used the ::, would look like this when you run echo on the result:

Invalid data :: 404 :: Syntax error

See the reference link I included for another example.

like image 59
jmort253 Avatar answered Jul 15 '26 10:07

jmort253



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!