Why is there a 1 at the end of my printed array?

非 Y 不嫁゛ 提交于 2020-01-24 05:19:12

问题


This is a super simple array print, but I'm getting at the end when I use print_r.

<?php 
  $user_names = array(1, 2, 3, 4);
  $results = print_r($user_names);
  echo $results;
?>

Then I get:

 Array
 (
     [0] => 1
     [1] => 2
     [2] => 3
     [3] => 4
 )
 1

回答1:


print_r already prints the array - there is no need to echo its return value (which is true and thus will end up as 1 when converted to a string):

When the return parameter is TRUE, this function will return a string. Otherwise, the return value is TRUE.

The following would work fine, too:

$results = print_r($user_names, true);
echo $results;

It makes no sense at all though unless you don't always display the results right after getting them.




回答2:


You get it because of

echo $results;

Since $results contains the result of print_r function which is TRUE (1)

print_r can return the string instead of echoing it. To do this, you must pass a second argument - true:

$results = print_r($user_names, true);

So, you have two options. Either remove echo $results or leave it, but pass a second argument to print_r.




回答3:


print_r prints the result in the screen, if you need to return a string instead of printing, you should pass a second argument to the function:

<?php 
$user_names = array(1, 2, 3, 4);
$results = print_r($user_names, true);
echo $results;

More info: http://php.net/manual/en/function.print-r.php




回答4:


print_r actually prints out the results, if you would like it to return the results, use print_r($user_name, true)'

so either of these will do what you want.

<?php 
  $user_names = array(1, 2, 3, 4);
  print_r($user_names);
 ?>

or

 <?php 
   $user_names = array(1, 2, 3, 4);
   $results = print_r($user_names,true);
    echo $results;
   ?>



回答5:


Since you gave print_r no second argument, it will do the printing itself and return a 1. you then save this one and print it. Try:

$results = print_r($user_names, true);

Check out the docs for print_r:

If you would like to capture the output of print_r(), use the return parameter. When this parameter is set to TRUE, print_r() will return the information rather than print it.



来源:https://stackoverflow.com/questions/14145821/why-is-there-a-1-at-the-end-of-my-printed-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!