简体   繁体   中英

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

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

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.

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.

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

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;
   ?>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM