Difference between echo and print_r in php? [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What’s the difference between echo, print, and print_r in PHP?
I am able to use both of these with seemingly the same effect. Is there a difference between the two? And is one preferred over the other?
Thanks!

The difference is that print_r recursively prints an array (or object, but it doesn't look as nice), showing all keys and values. echo does not, and is intended for scalar values.

$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
echo array($a); // returns "Array"
print_r($a); // returns
Array
(
[a] => apple
[b] => banana
[c] => Array
(
[0] => x
[1] => y
[2] => z
)
)

print_r prints human-readable information about a variable, while echo is used only for strings.

Echo just gives the value, print_r gives more information about the variable itself, such as the type of data and the elements in the array, if applicable.

I think you must mean print and echo rather than print_r.... print_r is very clearly different.
First, check out the docs. On the surface, there isn't much difference:
http://php.net/manual/en/function.print.php
http://php.net/manual/en/function.echo.php
The main difference is that print can behave as a function OR a language construct. Either of these will work:
print('Something');
print 'Something';
The former method (with the parenthesis) returns a value after it prints. Now, this begs the question "Why would I need a return value after printing?" The answer is, simply, you don't. The two methods of output are both language constructs, and there isn't a clear performance difference between the two. On an extremely large scale, echo may be marginally faster than print because of the return value, but it is so negligible as to be almost impossible to measure.
There are some tricks you can do to take advantage of the fact that print will behave like a function, though I am hard pressed to give you a real-world example. Here's a not-so-realistic example:
if (print('Test')) {
// do something after the string is printed
}
Again, not so useful, but there you have it.

Related

PHP ksort unexpected behavior [duplicate]

This question already has answers here:
ksort produces wrong result when dealing with alphanumeric characters
(6 answers)
Closed 4 years ago.
Let me tell you from the start: I know about the sort flags of this function. When I use SORT_STRING it works well, but the default flag SORT_REGULAR works weird, or doesn't work at all.
Consider an array like below.
$arr = [
'27a' => 'foo',
'27b' => 'foo',
'27c' => 'foo',
'27' => 'foo',
];
When I try to sort using ksort, it gives an array without being sorted in any obvious logic.
ksort($arr);
print_r($arr);
// this prints
Array
(
[27a] => foo
[27] => foo
[27b] => foo
[27c] => foo
)
As one could say the keys are neither numerically nor alphanumerically nor naturally sorted. Even more strangely, when I change the order of the source array, it gives a different result:
$arr = [
'27a' => 'foo',
'27' => 'foo',
'27b' => 'foo',
'27c' => 'foo',
];
ksort($arr);
print_r($arr);
// this prints
Array
(
[27b] => foo
[27c] => foo
[27] => foo
[27a] => foo
)
Does anyone know the logic behind this? Is this a bug or am I missing something?
EDIT: Thank you all for being interested in and answering my question. Although it's marked as duplicate, the other question didn't mention the weirder part: Why changing the order of the source array changes the result? It should give the same result with the same input set. Shall we discuss this too?
The reason that is happening is because it sees keys like '27a' as a string, and keys like '27' as an integer, even though it is quoted. You'll see the same results if you remove the quotes from the 27 key.
And, as the ksort page says: "Warning: Be careful when sorting arrays with mixed types values because sort() can produce unpredictable results."
Weird behavior for sure- unfortunately the best way to produce expected results when you have keys that look like integers (even if they are strings), is to specify the sort flag like SORT_STRING to ensure that you get the expected results every time.

Show array as written with rand inside

I have an array such as:
$var = array('hi','ho',rand(2,5));
What I would like to echo is the entire array, exactly as written.
Normally when you try a print_r, it shows as:
Array (
[0] => hi
[1] => ho
[2] => 3
)
But I want:
Array (
[0] => hi
[1] => ho
[2] => rand(2,5)
)
You can get this with file_get_contents, but is there any way to do so within the actual PHP file?
I don't think it's possible because when array is created, random value is assigned to element with index 2 and you cannot check how this value was created.
I don't think it's possible, since the rand is already evaluated as soon as you set the array to some variable.
A workaround would be the hold the expression as a string and then eval it when you need it. Like this:
$varStr = "array('hi','ho',rand(2,5))";
echo $varStr;
// when you actually need it
$var = eval($varStr);
However, this is almost never a good idea. Providing a use-case where you need this might help come up with a better solution.

Search sub arrays for specific key [duplicate]

This question already has answers here:
How to search by key=>value in a multidimensional array in PHP
(17 answers)
Closed 9 years ago.
What's the most efficient way to search an array element's sub arrays to check the value of a specific key? For example, given the following array, where I want to check both subarrays "msg" value, and if either is populated, return a boolean result:
[TGMN02] => Array
(
[2] => Array
(
[id] => 93143
[msg] =>
)
[3] => Array
(
[id] => 24876
[msg] =>
)
)
What I have at the moment is simply looping through and checking, which feels quite clunky.
I don't know about "most" efficient but this won't necessarily have to iterate through the whole array as it breaks the loop on the first value found, so technically more efficient.
function hasMsg($a){
foreach($a as $b)
if(!empty($b['msg'])) return true;
return false;
}
Okay... since some meager comments weren't accompanied by alternative suggestions - you could try using some PHP>5.3 - I really can't see how it would be any more efficient though - it must still loop through the array at some level (but I'm not 100% sure on the inner workings of the PHP interpreter - perhaps there is some internal magic that could speed things up), so this is probably purely aesthetic:
$hasMsg = !!(count(array_filter($a,function($b){ return !empty($b['msg']); })));
... if anything less efficient. There's nothing wrong with "looping" through an array - it's a tried and tested language construct that's been around since the dawn of digital time (almost).
First write some custom func and then try to use it with array_walk_recursive(array &$input , callable $funcname [, mixed $userdata = NULL ]) function. Php manual.

Php regexp get the strings from array print_r like string

Im trying to list out here how to match strings that looks like array printr.
variable_data[0][var_name]
I would like to get from above example 3 strings, variable_data, 0 and var_name.
That above example is saved in DB so i same structure of array could be recreated but im stuck. Also a if case should look up IF the string (as above) is in that structure, otherwise no preg_match is needed.
Note: i dont want to serialize that array since the array 'may' contain some characters that might break it when unserializing and i also need that value in the array to be fully visible.
Any one with regexp skills who might know the approach ?
Solution:
(\b([\w]*[\w]).\b([\w]*[\w]).+(\b[\w]*[\w]))
Thos 2 first indexes should be skipped... but i still get what i want :)
Not for nothing but couldn't you just do..
$result = explode('[', someString);
foreach ($result as $i => $v) {
$temp = str_replace(']'. ''. $result[$i]);
//Do something with temp
}
Obviously you need to edit the above a little bit depending on what you are doing but it is very simple and even gives you the same flexibility and you don't need to invoke the matching engine...
I don't think we build regex's here for people... instead please see http://regexpal.com/ for a Regex tester / builder with visual aid.
Furthermore people usually don't know how to use them properly which is then fostered by others creating the expressions for them.
Please remember complex expressions can have terrible performance overheads although there is nothing seemingly complex about your request...
Then after it is compelte post your completed RegEx and answer your own question for maximum 1337ne$$ :)
But since I am nice here is your reward:
\[.+\]\[\d+\]
or
[a-z]+_[a-z]+\[.+\]\[\d+\]
Depending on what you want to match out of the string (which you didn't specify) so I assumed all
Both perform as follows:
arr_var[name][0]; //Matched
arr_var[name]; //Not matched
arr_var[name][0][1];//Matched
arr_var[name][2220][11];//Matched
Again, test them and understand with visual aid at the above link.
Solution:
(\b([\w]*[\w]).\b([\w]*[\w]).+(\b[\w]*[\w]))
Those 2 first indexes should be skipped... but i still get what i want :)
Edit
Here is improved one:
$str = "variable[group1][parent][child][grandchild]";
preg_match_all('/(\b([\w]*[\w]))/', $str,$matches);
echo '<pre>';
print_r($matches);
echo '</pre>';
// Output
Array
(
[0] => variable
[1] => group1
[2] => parent
[3] => child
[4] => grandchild
)

Array: 4th dimension, isset return not reliable

Does anybody know, how it can be, that this code echoes yahoo? There is clearly no 4th array with the key 'something', but it keeps thinking it's like that. Bug? Feature?
$array = array('a' => array('b' => array('c' => 'test')));
echo '<pre>';
var_dump($array);
echo '</pre>';
if (isset($array['a']['b']['c']['something'])) {
echo 'yahoo';
}
Because PHP thinks you are checking the 'something'th place of the string 'test'. Remember, strings are arrays of characters. try to echo $array['a']['b']['c']['something'].
::EDIT::
I Explained it, I didn't say it made sense. :P
Here has discussed the behavior of PHP in this issue and provides a solution that is exactly for your problem.
You'd want to use is_array($array['a']['b']['c']) rather than isset($array['a']['b']['c']['something']) in this case, or maybe a crafty combination of the two to make sure you don't get any errors if it's not set when you're checking to see if it's an array.
Something like:
if(isset($array['a']['b']['c']['something']) && is_array($array['a']['b']['c'])){ [...] }

Categories