1

I have a variable and when I output it with print_r like this:

print_r($sort_order[$field->name]);

I get this:

Array ( [0] => Array ( [sort_order] => 92 ) ) 

but I only need the value which is 92. How can I do so it outputs only that when echoing it? example:

echo $sort_order[$field->name];

should output simple

92
mhall
  • 3,671
  • 3
  • 23
  • 35
Cain Nuke
  • 2,843
  • 5
  • 42
  • 65
  • 1
    Exactly as you have it. `echo $array_name["sort_order"];` – Lock Sep 04 '15 at 07:19
  • And whats the $array_name? – Cain Nuke Sep 04 '15 at 07:27
  • What ever the name of your array is. Your post is slightly confusing. You are using `print_r` on a variable called `$sort_order`, yet the results of the print_r show an array key called `sort_order`. If this is actual correct (in that you have an array variable called `$sort_order` as well as an array key called `$sort_order`, then you would be using `echo $sort_order["sort_order"];` – Lock Sep 04 '15 at 07:28
  • My array is $sort_order. So should it be $sort_order["sort_order"] – Cain Nuke Sep 04 '15 at 07:30

3 Answers3

1

The print_r() function is used to print human-readable information about a variable.

You can do both print and echo to output the required value:

echo $sort_order[$field->name];

print $sort_order[$field->name];

Hope this helps.

Navneet
  • 4,543
  • 1
  • 19
  • 29
  • The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. – Navneet Sep 04 '15 at 07:24
  • Your field is actually an array of arrays. So you have to access the element by its index. – Navneet Sep 04 '15 at 07:36
1

Your $sortOrder array is actually an array of arrays, like:

[
    [ 'sort_order' => 92 ]
]

That's why you can't print it like you expect.

Try:

echo $sort_order[0]['sort_order'];

Output:

92
mhall
  • 3,671
  • 3
  • 23
  • 35
  • Oh, nevermind, this was the solution after all, I had ane rror somewhere else and after fixing that it works. Thank you. – Cain Nuke Sep 04 '15 at 07:36
0

The command print_r displays the variable in a human readable way. So if you need to know all the info in a variable (in particular for large arrays), then you use that. For other use, e.g. when you only need to know the content (in I guess 99.999% of all the cases) you should either use echo as you already mentioned it or print (althoug, they are more or less the same).

Please consider this links for futher information

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

What's the difference between echo, print, and print_r in PHP?

Community
  • 1
  • 1
rst
  • 2,510
  • 4
  • 21
  • 47