php 如何在php数组中使用echo以字符串形式返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10051451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:15:00  来源:igfitidea点击:

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

phparrays

提问by droidus

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

回答by jmort253

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

使用PHP 内爆将您的 Array 转换为您可以回显的字符串。在数组上使用 echo 只会显示数据类型。

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 echoon the result:

那么你的字符串,如果你使用 ::,当你运行echo结果时看起来像这样:

Invalid data :: 404 :: Syntax error

See the reference link I included for another example.

有关另一个示例,请参阅我包含的参考链接。

回答by Luke Shaheen

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

你需要遍历你的数组。有多种方法可以做到这一点,我个人更喜欢使用foreach循环。

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

例如,这将在新行上回显数组中的每个错误消息:

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

回答by Ariel

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 returnparameter set to True.

如果你想检查数组的内容,你可以使用的print_r()var_export()return参数集True

回答by David Rock

$list = array( 'one Thing', 'Two Things', 'The Things' );
echo implode( ", ", $list );

$list = array( '一件事', '两件事', '事情' );
回声内爆( ", ", $list );

Result One thing, two things, three things

结果 一件事,两件事,三件事

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

轻松愉快,希望它能帮助我知道我迟到了,但也许对其他人有用?