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.
Related
Bear with me, I'm learning.
I often see snippets like the one below:
<?p
$imageArray = get_field('image_field');
$imageAlt = $imageArray['alt'];
$imageURL = $imageArray['url'];
?>
It is pedagogical and clear and organized. But is it necessary to get the entire array before querying the array for values? Can I not define the variable in just a single line? Something like the below (which doesn't work, neither the other variants I have tried):
$imageAlt = get_field('image_field', ['alt']);
$imageURL = get_field('image_field', ['url']);
Yes, you can.
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. - Source
$imageAlt = get_field('image_field')['alt'];
https://eval.in/548036
The question you are asking can be answered by asking 2 questions:
Is it doable ?
Is it a good idea to do it that way ?
Is it doable ?
Yes! You do not have to store the array in a variable and re-use it later.
For instance, you could do:
$imageAlt = get_field('image_field')['alt'];
Note: This will work in PHP 5.4+ and is called: Array dereferencing.
But that is not the only consideration...
Is it a good idea to do it that way ?
No. It's not a good idea in many cases. The get_field() function, depending on your context, is probably doing a lot of work and, each time you call it, the same work is don multiple times.
Let's say you use the count() function. It will count the number of items in an array. To do that, it must iterate through all items to get the value.
If you use the count() function each time you need to validate number of items in an array, you are doing the task of counting each and every time. If you have 10 items in your array, you probably won't notice. But if you have thousands of items in your array, this may cause a delay problem to compute your code (a.k.a. it will be slow).
That is why you would want to do something like: $count = count($myArray); and use a variable instead of calling the function.
The same applies to your question.
While PHP 5.4+ allows you to directly dereference a function return value like this:
get_field('image_field')['alt']
...in this particular case I would not suggest you do so, since you're using two values from the resulting array. A function call has a certain overhead just in itself, and additionally you don't know what the function does behind the scenes before it returns a result. If you call the function twice, you may incur a ton of unnecessary work, where a single function call would have done just as well.
This is not to mention keeping your code DRY; if you need to change the particulars of the function call, you now need to change it twice...
PHP allows you to play around quite a bit:
function foo(){
return array('foo' => 1, 'bar' => 2);
}
Option 1
echo foo()['foo']; // 1
# Better do this if you plan to reuse the array value.
echo ($tmp = foo())['foo']; // 1
echo $tmp['bar']; // 2
It is not recommended to call a function that returns an array, to specifically fetch 1 key and on the next line doing the same thing.
So it is better to store the result of the function in a variable so you can use it afterwards.
Option 2
list($foo, $bar) = array_values(foo());
#foo is the first element of the array, and sets in $foo.
#bar is the second element, and will be set in $bar.
#This behavior is in PHP 7, previously it was ordered from right to left.
echo $foo, $bar; // 12
Option 3
extract(foo()); // Creates variable from the array keys.
echo $foo, $bar;
extract(get_field('image_field'));
echo $alt, $url;
Find more information on the list constructor and extract function.
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.
I have a string like this stored in mysql table:
?name1=value1&name2=value2&name3=value3
originally this data was only going to be used to send GET data to another script but now i find myself needing it for other things.
is there a predefined function in PHP for turning these pairs into variable or an array? or will I have to do it manually?
The (poorly-named) PHP function parse_str can do this, though you will need to first trim off the initial question mark.
$arr = array();
parse_str($str, $arr);
print_r($arr);
There are some caveats to this function alluded to in the manual page:
If you call it without the second array parameter it will write the values into the current scope as local variables. This can be dangerous if the string contains keys that may change the value of variables already present in your program.
The magic_quotes_gpc setting affects how this function operates, since this is the routine used internally by PHP to decode query strings and urlencoded POST bodies.
If you need a portable solution that is not affected by the magic_quotes_gpc setting then it's reasonably straightforward to write a decoding function manually, using urldecode to handle the value encoding:
function parseQueryString($queryString) {
$result = array();
$pairs = explode("&", $queryString);
foreach ($pairs as $pair) {
$pairArr = split("=", $pair, 2);
$result[urldecode($pairArr[0])] = urldecode($pairArr[1]);
}
return $result;
}
This solution will probably be slightly slower than the built-in parse_args function, but has the benefit of consistent behavior regardless of how PHP is configured. Of course you will again need to first strip off the ? from the beginning, which is not included in either example.
Var_export Might be useful.
$arr=?name1=value1&name2=value2&name3=value3
var_export($arr);
eg. I want to replace instances of some words with their string length
"XXXX is greater than XX" becomes "4 is greater than 2"
Code that I intend to write :
$myStrings = Array("XX","XXX","XXXX","XXXXX");
$outStr = str_replace($myStrings,strlen(current($myStrings)),$outStr);
But here CURRENT is not working.
P.S. Please do not suggest workarounds to do this stuff since that is not what I intend to ask the forum. My query is getting current pointer to an array being traversed internally.
Thank You.
The function you are looking for is array_map. It applies a function to all elements of an array and outputs the results as a new array:
$myStrings = Array("XX","XXX","XXXX","XXXXX");
$outStr = str_replace($myStrings,array_map('strlen', $myStrings)),$outStr);
This might create a new problem as XXXX will be replaced with 22 before XXXX is checked. The solution to this would be reverse the input array:
$myStrings = array_reverse(Array("XX","XXX","XXXX","XXXXX"));
$outStr = str_replace($myStrings,array_map('strlen', $myStrings)),$outStr);
I don't think you can. Since it's an internal implementation, what would PHP expose to you that you could use to determine the current element?
Note that this is different from accessing internal array pointers using current(), key(), next(), reset() et al. I'm referring to the fact that PHP has an internal implementation of str_replace() for handling replacements of arrays of strings.
A quick test reveals that PHP doesn't even seem to bother with array pointers when replacing them with str_replace() anyway:
$arr = array('a', 'b', 'c'); // Internal pointer is at a
$str = 'abc';
next($arr); // Internal pointer is at b
echo str_replace($arr, 'x', $str), "\n"; // xxx
echo current($arr), "\n"; // b
Oh, by the way, this is what the manual for str_replace() says (strong emphasis mine):
If search is an array and replace is a string, then this replacement string is used for every value of search.
So specifically for str_replace(), I don't think it was ever intended for you to pass in a replacement string that is dynamic based on the input array.
And http://www.php.net/manual/de/function.array-walk.php isnĀ“t an option?
Can't wrap my head around this...
Say, we explode the whole thing like so:
$extract = explode('tra-la-la', $big_sourse);
Then we want to get a value at index 1:
$finish = $extract[1];
My question is how to get it in one go, to speak so. Something similar to this:
$finish = explode('tra-la-la', $big_sourse)[1]; // does not work
Something like the following would work like a charm:
$finish = end(explode('tra-la-la', $big_sourse));
// or
$finish = array_shift(explode('tra-la-la', $big_sourse));
But what if the value is sitting somewhere in the middle?
Function Array Dereferencing has been implemented in PHP 5.4. For older version that's a limitation in the PHP parser that was fixed in here, so no way around it for now I'm afraid.
Something like that :
end(array_slice(explode('tra-la-la', $big_sourse), 1, 1));
Though I don't think it's better/clearer/prettier than writing it on two lines.
you can use list:
list($first_element) = explode(',', $source);
[1] would actually be the second element in the array, not sure if you really meant that. if so, just add another variable to the list construct (and omit the first if preferred)
list($first_element, $second_elment) = explode(',', $source);
// or
list(, $second_element) = explode(',', $source);
My suggest - yes, I've figured out something -, would be to use an extra agrument allowed for the function. If it is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string. So, if we want to get, say, a value at index 2 (of course, we're sure that the value we like would be there beforehand), we just do it as follows:
$finish = end(explode('tra-la-la', $big_sourse, 3));
explode will return an array that contains a maximum of three elements, so we 'end' to the last element which the one we looked for, indexed 2 - and we're done!