Peter
Peter

Reputation: 73

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

Upvotes: 4

Views: 2879

Answers (5)

Foggzie
Foggzie

Reputation: 9821

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.

Upvotes: 0

Doon
Doon

Reputation: 20232

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

Upvotes: 0

m4t1t0
m4t1t0

Reputation: 5731

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

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318518

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.

Upvotes: 11

Wojciech Zylinski
Wojciech Zylinski

Reputation: 2035

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.

Upvotes: 0

Related Questions