7

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

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

how would I modify my current code to add something like you provided in the second example, with the "::"?
5

You need to loop through your array. There are multiple ways of doing this, with my personal preference being using a foreach loop.

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

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

1 Comment

The advantage here is that your errors object is still an array. +1
4
$list = array( 'one Thing', 'Two Things', 'The Things' );
echo implode( ", ", $list );

Result One thing, two things, three things

Easy breezy, hope it helps i know i'm late but useful to someone else maybe?

Comments

2

You can't echo out an array's content as-is.

If you want to check the array's contents, you can use print_r() or var_export() with the return parameter set to True.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.