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'])){ [...] }
Related
Can anybody provide an example of when php's list() function is actually useful or preferable over some other method? I honestly can't think of a single reason I'd ever actually want/need to use it..
Got a simple sql result row (numeric), containing, say, an ID and a name?
A simple solution to deal with it, can be:
list($id,$name)=$resultRow;
Edit;
or here's another: you want to know the current key/value pair of an array
list($key,$val)=each($arr);
this can even be put into a loop
while (list($key,$val)=each($arr))
altho you could say a foreach is exactly this; but if the
$arr changes in the meantime, well then it's not. It has its uses. :)
It's a handy function when you know the right hand side is returning an indexed array of a certain size.
list($basename, $ext) = explode('.', 'filename.png');
Note that it can be used in PHP 5.5 with foreach:
$data = [
['a1', 'b1'],
['a2', 'b2'],
];
foreach ($data as list($a, $b))
{
echo "$a $b\n";
}
But if you prefer more verbose code, then I doubt you'll think the above is "better" than the alternatives.
more out of interested...
$_GET['unique'] = blahblahblah=this_is_what_im_interested_in
I know I can get the second element like this:
$words = explode('=', $_GET['unique']);
echo $words[1];
Is there a way to get this in a single line? - that would then 'hopefully' allow me to add that to function/object call:
$common->resetPasswordReply(... in here I would put it....);
like
$common->resetPasswordReply(explode('=', $_GET['unique'])[1]);
I'm just interested to see if this is possible.
PHP supports the indexing on functions if they are returning arrays/objects; so the following would work too:
echo explode('=', $_GET['unique'])[1];
EDIT
This is termed as array dereferencing and has been covered in PHP documentations:
As of PHP 5.4 it is possible to array dereference the result of a
function or method call directly. Before it was only possible using a
temporary variable.
As of PHP 5.5 it is possible to array dereference an array literal.
This should do it for you.
substr($str, strpos($str, "=")+1);
Strangely enough you can 'almost' do this with list(), but you can't use it in a function call. I only post it as you say 'more out of interest' :-
$_GET['unique'] = "blahblahblah=this_is_what_im_interested_in";
list(, $second) = explode('=', $_GET['unique']);
var_dump($second);
Output:-
string 'this_is_what_im_interested_in' (length=29)
You can see good examples of how flexible list() is in the first set of examples on the manual page.
I think it is worth pointing out that although your example will work:-
$common->resetPasswordReply(explode('=', $_GET['unique'])[1]);
it does kind of obfuscate your code and it is not obvious what you are passing into the function. Whereas something like the following is much more readable:-
list(, $replyText) = explode('=', $_GET['unique']);
$common->resetPasswordReply($replyText));
Think about coming back to your code in 6 months time and trying to debug it. Make it as self documenting as possible. Also, don't forget that, as you are taking user input here, it will need to be sanitised at some point.
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.
Trying to create a variable with unique name for each $item.
To prevent error "Only variables can be passed by reference".
If there are 5 items in array $items, we should get 5 unique variables:
$item_name_1;
$item_name_2;
$item_name_3;
$item_name_4;
$item_name_5;
All of them should be empty.
What is a true solution for this?
You can dynamically create variable names doing the following:
$item_name_{$count} = $whatever;
I must warn you though, this is absolutely bad style and I've never seen a good reason to use this. In almost every use case an array would be the better solution.
Well, I guess that you can use $item_name_{$count} = "lorem ipsum"; for it
... But won't be better to use an array?
I'm not sure I understand what you want to do, so this may be completely wrong. Anyway, if what you want is an array with empty values you can use this code:
<?php
$arr = array_fill(0, 3, '');
var_export($arr) // array ( 0 => '', 1 => '', 2 => '', 3 => '', )
?>
See array_fill for more information.
If this is the wrong answer, please clarify what you mean. I may be able to help you.
I have tried to do this:
<?=implode(array('A','B','C'));
To display an array but was wondering if there was an easier way of showing an array?
I tried
<?=print_r(array('A','B','C'));
But it actually displays an array structure. I want the string to be like ABC.
No, there is no easier way than this implode.
Normally while debugging array printing is done using implode() and print_r(). If you want to display the arrays in your different way, just create your own function for that.
I have seen in many examples var_dump(...).
link text
Yeah, sure... If you always want an array to display, say, with each element on a new line, you can just write your own function (with a really short name... if you are just that lazy... [not recommended...])!
<?php
// To Call Function:
$array = array(2,3,4,5,'awesome!');
ez($array);
/* echoes:
2
3
4
5
awesome!
*/
// Poorly named function...
function ez($array = array()) {
if(!$array || empty($array)) return;
$output = implode('\n',$array);
echo "<pre>{$output}</pre>";
}
?>
Sorry, this is kind of a smartass answer.