I'm just starting out learning PHP, learning from a few sources. I would like to know why the print_r function requires the boolean value.
<?php
$names = array('Jeff','James','Jeremy');
echo '<pre>', print_r($names), '</pre>';
?>
OUTPUT:
Array
(
[0] => Jeff
[1] => James
[2] => Jeremy
)
If i don't include the boolean value, the output comes with an integer "1" at the end of the array. Like this:
Array
(
[0] => Jeff
[1] => James
[2] => Jeremy
)
1
Can anybody help me out with this? Would be greatly appreciated.
Thanks
Specifying the second argument as true means that print_r returns the contents for you to do something with, mostly store in a variable. Specifying it as false, or omitting it, means the contents get printed.
according to the documentation at php.net the boolean suppresses the output and returns it (using output buffers).
at this point of code, this makes no sense, until you want to assign the output of print_r() into a variable.
So these both lines are in fact the same:
echo print_r($names, true);
print_r($names);
see docu for details: http://php.net/manual/en/function.print-r.php
since you just edited your question, here is the answer:
you want to put pre-tags arouond your code. and usually you want to escape html-characters.
so you suppress the output to get it parsed by a call of htmlspecialchars()
echo '<pre>', htmlspecialchars(print_r($names,true)) , '</pre>';
Related
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
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
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.
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?
I been looking thru the posts here all day but can't figure out what I'm doing wrong. (I'm new to php and json)
Here is my code that work.
$json = '{"id":1234,"img":"1.jpg"}';
$data = json_decode($json, true);
echo $data["img"];
But when the json respond is this
$json = '{"demo1":[{"id":1234,"img":"1.jpg"}],"userId":1}';
it's a big harder for me. then img is a child of demo1? How to get it?
Thx. :)
Figuring out the array indices
As you're new to PHP, I'll explain how to figure out the array indces of the required array value. In PHP, there are many functions for debugging — print_r() and var_dump() are two of them. print_r() gives us a human-readable output of the supplied array, and var_dump() gives us a structured output along with the variable types and values.
In this case, print_r() should suffice:
$json = '{"demo1":[{"id":1234,"img":"1.jpg"}],"userId":1}';
$data = json_decode($json, true);
// wrap the output in <pre> tags to get a prettier output
echo '<pre>';
print_r($data);
echo '</pre>';
This will produce the following output:
Array
(
[demo1] => Array
(
[0] => Array
(
[id] => 1234
[img] => 1.jpg
)
)
[userId] => 1
)
From there, it should be pretty easy for you to figure out how to access the required vaule.
$data['demo1'][0]['img'];
Creating a helper function for ease of use
For ease of use, you can create a helper function to make this process easier. Whenever you want to view the contents of an array, you can simply call dump_array($array); and be done with it. No more messing around with <pre> tags or print_r().
Function code:
function dump_array($array) {
echo '<pre>' . print_r($array, TRUE) . '</pre>';
}
Usage example:
$arr = ['foo' => range('a','i'), 'bar' => range(1,9)];
dump_array($arr);
after decoding :
echo $data->demo[0]->img;
Basically, a { in JSON leads to a -> (it's an object).
And a [ to a [], it's an array.
echo "{$line['text_1']}";
the above echo works fine ,however when it comes to 2d array, in my sublime, only {$line['text_2']} this part work fine. output error both sublime and browser
echo "$array_2d[{$line['text_1']}][{$line['text_2']}]";
any idea?
update
echo "$array_2d[$line['text_1']][$line['text_2']]";
using xampp, error Parse error: syntax error, unexpected '[', expecting ']' in C:\xampp\htdocs
and I'm just outputting a value from the mysql_fetch_assoc. I can do it in another way by echo '' however I'm trying to make my code easier for future editting and code copy paste
and yes I'm doing things like
echo "The price is $array_2d[$line['text_1']][$line['text_2']]"
with lots of html code in the double quote.
Why are you trying to output the array?
if it is for debugging purposes, you can just use the native php functions print_r() or var_dump()
You should be able to say
echo "item is {$array_2d[$line['text1']][$line['text2']]}";
to get to a subelement.
Of course, this is only really useful when it's not the only thing in the string. If you're only echoing the one value, you don't need the quotes, and things get simpler.
echo $array_2d[$line['text1']][$line['text2']];
this should work :
echo $array_2d[$line['text_1']][$line['text_2']];
When echoing variables, you don't have to use the quotes:
echo $array_2d[$line['text_1']][$line['text_2']];
If you do need to output something with that string, the concatentation operator can help you:
echo "Array: " . echo $array_2d[$line['text_1']][$line['text_2']];
You can use print_r() to echo the array.
e.g.:
print_r($array);
Output will be:
Array ( [test] => 1 [test2] => 2 [multi] => Array ( [multi] => 1 [multi2] => 2 ) )
Also you can use this to make it more readable in a HTML context:
echo '<pre>';
print_r($array);
echo '</pre>';
Output will be:
Array
(
[test] => 1
[test2] => 2
[multi] => Array
(
[multi] => 1
[multi2] => 2
)
)
You can use print_r() or var_dump() to echo an array.
The print_r() displays information about a variable in a way that's readable by humans whereas the var_dump() function displays structured information about variables/expressions including its type and value.
$array = 'YOUR ARRAY';
echo "<pre>";
print_r($array);
echo "</pre>";
or
$array = 'YOUR ARRAY';
var_dump($array);
Example variations
I'm wondering why you would try using the $line array as a key to access data in $array_2d.
Anyway, try this:
echo($line['text_1'].'<br>');
this:
echo($array_2d['text_1']['text_2'].'<br>');
and finally this (based on your "the $line array provides the keys for the $array_2d" array example)
$key_a = $line['text_1'];
$key_b = $line['text_2'];
echo($array_2d[$key_a][$key_b].'<br>');
Which can also be written shorter like this:
echo($array_2d[$line['text_1']][$line['text_2']].'<br>');
Verifying/Dumping the array contents
To verify if your arrays hold the data you expect, do not use print_r. Do use var_dump instead as it will return more information you can use to check on any issues you think you might be having.
Example:
echo('<pre>');
var_dump($array_2d);
echo('</pre>');
Differences between var_dump and print_r
The var_dump function displays structured information of a variable (or expression), including its type and value. Arrays are explored recursively with values indented to show structure. var_dump also shows which array values and object properties are references.
print_r on the other hand displays information about a variable in a readable way and array values will be presented in a format that shows keys and elements. But you'll miss out on the details var_dump provides.
Example:
$array = array('test', 1, array('two', 'more'));
output of print_r:
Array
(
[0] => test
[1] => 1
[2] => Array
(
[0] => two
[1] => more
)
)
output of var_dump:
array(3) {
[0]=> string(4) "test"
[1]=> int(1)
[2]=> array(2)
{
[0]=> string(3) "two"
[1]=> string(4) "more"
}
}
When I attempt to determine if a user is in an array of users, for some reason it is only returning true when the user is in the 0th position.
For the life of me I cannot figure out what I am doing wrong.
This does not echo "True"
echo $usersign; // RDW
print_r($these_analysts[0]); // Array ( [0] => JKB [1] => RDW )
if(in_array($usersign,$these_analysts[0])){
echo "True";
}
This echoes "True"
echo $usersign; // RDW
print_r($these_analysts[0]); // Array ( [0] => RDW [1] => CLM )
if(in_array($usersign,$these_analysts[1])){
echo "True";
}
EDIT:
vardump gives a much more comprehensive view of the array, whereas print_r did show the trailing spaces, it didn't catch my eye.
For some reason the first element of each array was giving string3, and all others were giving string4.
You have a lot of syntax errors.
When you use strings, it is always better prace to put strings in single or double quotes. It doesn't matter which one (as far as speed is concerned).
Also, you need commas between the elements.
I entered the following code and it works.
$usersign = 'RDW';
$these_analysts[0] = array( 'JKB', 'RDW' );
print_r( $these_analysts );
if(in_array($usersign,$these_analysts[0])) echo "True";
Try:
$usersign = 'RDW';
$these_analysts[1] = Array ( 0 => 'RDW', 1 => 'CLM' );
if(in_array($usersign,$these_analysts[1])){
echo "True";
}
That should work.
This is happening (at least in my testing) if you specify RDW as a constant without defining these constants before using them. If you put your initials in double-quotes (i.e. use explicit strings) then everything works fine. If you want to use them as constants, then define these constants first:
define("RDW","RDW");
define("JKB","JKB");
And then your code works as expected again.
You're missing ; on half of your lines, you're using base strings instead of " around them, and your Array syntax is invalid (should be Array("JKB","RDW");). Maybe if these are fixed it might have a chance of working.
You have punctuation errors:
$these_analysts[0] = Array ( [0] => JKB [1] => RDW )
should be
$these_analysts = Array ( 0 => "JKB", 1 => "RDW" );
*This is the actual way you need to do *
$usersign = 'RDW';
$these_analysts = array ( 0 => 'RDW', 1 => 'CLM' );
if(in_array($usersign,$these_analysts)){
echo "True";
}
I have the following array (in php after executing print_r on the array object):
Array (
[#weight] => 0
[#value] => Some value.
)
Assuming the array object is $arr, how do I print out "value". The following does NOT work:
print $arr->value;
print $val ['value'] ;
print $val [value] ;
So... how do you do it? Any insight into WHY would be greatly appreciated! Thanks!
echo $arr['#value'];
The print_r() appears to be telling you that the array key is the string #value.
After quickly checking the docs, it looks like my comment was correct.
Try this code:
print $arr['#value'];
The reason is that the key to the array is not value, but #value.
You said your array contains this :
Array (
[#weight] => 0
[#value] => Some value.
)
So, what about using the keys given in print_r's output, like this :
echo $arr['#value'];
What print_r gives is the couples of keys/values your array contains ; and to access a value in an array, you use $your_array['the_key']
You might want to take a look at the PHP manual ; here's the page about arrays.
Going through the chapters about the basics of PHP might help you in the future :-)