Could someone explain me this while loop for PHP? - php

Could some one explain me this while loop?
while (list($key, $value) = each($HTTP_GET_VARS)) {
$get_url .= $key . '=' . $value . '&';
}
I know its silly but many times silly things makes huge difference....

$HTTP_GET_VARS is a deprecated array that contains the parameters passed in the querystring. each() is a function that iterates through an array and returns an array consisting of the key and value of the "current" element of the array. list() is a language construct that explodes an array assigned to it into the variables passed to it.
When the end of the array is reached, each() returns a false value, causing the loop to exit.

The each() function returns the current key and value for the given array, and then moves the array pointer (the current item) forward by one.
Therefore, calling it multiple times is a way to iterate through the items in the array in order, and when you reach the end, each() just stops returning a value.
The list() is not a function but a language construct; it's a shortcut for setting multiple variables at once. In the example posted it sets $key to the first value in the array returned by each() (the current key) and $value to the second (the current value).
There's a number of problems with that code snippet.
You should reset the array pointer before you use each() like this, because you shouldn't assume that the array pointer is at the start by the time this code executes.
The values it is concatenating into a query string should be escaped (eg. by urlencode()).
It's also leaving a separating '&' character at the end of the query string unnecessarily.
$HTTP_GET_VARS is a deprecated feature of PHP; it should be replaced with $_GET.
Iterating over an array with foreach () is cleaner and easier to read than while, list, each like this, and may be faster too.

each returns an array containing the current key and value, as you iterate through an array. list lets you unpack an array into multiple variables. I find the foreach construct much more clear.
foreach ($some_array as $key => $value)
{
...
}
As noted by Ignacio, HTTP_GET_VARS is deprecated. You can use $_GET instead.

The loop goes through each of the pairs of HTTP GET parameters in the array $HTTP_GET_VARS, assigning the sides of the pair to two variables $key and $value in that order.
The assignment 'returns' its value, hence, at the end of the array, each() will return false, which despite the assignment will cause the while condition to abort.
Inside the loop, each of $key and $value are appended to the string $get_url with some formatting.

Related

Why should I use reset($arr) instead of $arr[0] in php to yield the first element of an Array in php? [duplicate]

Which one would you use?
Basically I only want to get the 1st element from a array, that's it.
Well, they do different things.
array_shift($arr) takes the first element out of the array, and gives it to you.
$arr[0] just gives it to you... if the array has numeric keys.
An alternative that works for associative arrays too is reset($arr). This does move the array's internal pointer, but unless you're using those functions this is unlikely to affect you.
array_shift will actually remove the specified value from the array. Do not use it unless you really want to reduce the array!
See here: http://php.net/manual/en/function.array-shift.php
You would use $arr[ 0 ]; array_shift removes the first element from the array.
EDIT
This answer is actually somewhere between incomplete and plain out wrong but, because the comments of the two jon's I think that it should actually stay up so that others can see that discourse.
The right answer:
reset is the method to return the first defined index of the array. Even in non-associative arrays, this may not be the 0 index.
array_shift will remove and return the value which is found at reset
The OP made the assumption that $arr[0] is the first index is not accurate in that particular context.
$arr[0] only works if the array as numerical keys.
array_shift removes the element from the array and it modifies the array itself.
If you are not sure what the first key is , and you do not want to remove it from the array, you could use:
<?php
foreach($arr $k=>$v){
$value = $v;
break;
}
or even better:
<?php
reset($arr);
$value = current($arr);
If you have an associative Array you can also use reset($arr): It returns the first Element (doesn't remove), and sets the array pointer to this element.
But the fastest way is $arr[0].
Do you want to modify the arr array also? array_shift removes the first element of the array and returns it, thus the array has changed. $arr[0] merely gives you the first element.
I would use $arr[0] unless I explicitly wanted to modify the array. You may add code later to use the arr array and forget that it was modified.
given what you need, $arr[0] is preferrable, because it's faster. array_shift is used in other situations.
arrshift is more reliable and will always return the first element in the array, but this also modifies the array by removing that element.
arr[0] will fail if your array doesn't start at the 0 index, but leaves the array itself alone.
A more convoluted but reliable method is:
$keys = array_keys($arr);
$first = $arr[$keys[0]];
with array_shif you have two operations:
retrive the firs element
shift the array
if you access by index, actually you have only one operation.
If you want the first element of an array, use $arr[0] form. Advantages - Simplicity, Readability and Maintainability. Keep things straight forward.
Edit: Use index 0 only if you know that the array has default keys starting from 0.
If you don't want to change the array in question, use $arr[0] (which merely gets the first element), otherwise if you want to remove the first element of $arr from $arr, use array_shift($arr).
For example:
$arr=array(3,-6,2);
$foo=$arr[0]; //$foo==3 and $arr==array(3,-6,2).
$bar=array_shift($arr); //$bar==3 and $arr==array(-6,2).
ETA: As others have pointed out, be sure that your array isn't an associative array (ie the keys are 0,1,...,(sizeof($arr)-1)), otherwise this probably won't work.

Grabbing the name from data sent through post

When I send over post data I do a print_r($_POST); and I get something like this...
Array ( [gp1] => 9 )
Is there a way to get the "gp1", the name sent over as a value? I tried doing.
echo key($_POST["gp1"]);
But no luck there, I figured it would echo gp1. Is there a way to do this?
you need
print_r(array_keys($_POST));
check this for more details http://php.net/manual/en/function.array-keys.php
You could use foreach to see each key-value pair, or use array_keys to get a list of all keys.
foreach ($_POST as $key => $value) {
// Do whatever
}
Well, if you can write $_POST["gp1"] you already have the key anyway ;)
key() works differently, it takes an array as argument:
The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns NULL.
So if you have not done anything with the array (no traversing), key($_POST) would give you the key of the first element of the array.
Maybe you want a foreach loop?
foreach($_POST as $key => $value) {
}
There are other methods to retrieve keys as to well. It depends on what you want to do.

PHP scope question

I'm trying to look through an array of records (staff members), in this loop, I call a function which returns another array of records (appointments for each staff member).
foreach($staffmembers as $staffmember)
{
$staffmember['appointments'] = get_staffmember_appointments_for_day($staffmember);
// print_r($staffmember['appointments'] works fine
}
This is working OK, however, later on in the script, I need to loop through the records again, this time making use of the appointment arrays, however they are unavailable.
foreach ($staffmembers as $staffmember)
{
//do some other stuff
//print_r($staffmember['appointments'] no longer does anything
}
Normally, I would perform the function from the first loop, within the second, however this loop is already nested within two others, which would cause the same sql query to be run 168 times.
Can anyone suggest a workaround?
Any advice would be greatly appreciated.
Thanks
foreach iterates over a copy of the array. If you want to change the value, you need to reference it:
foreach($staffmembers as &$staffmember) // <-- note the &
{
$staffmember['appointments'] = get_staffmember_appointments_for_day($staffmember);
// print_r($staffmember['appointments'] works fine
}
From the documentation:
Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.
and
As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.

remove duplicate from string in PHP

I am looking for the fastest way to remove duplicate values in a string separated by commas.
So my string looks like this;
$str = 'one,two,one,five,seven,bag,tea';
I can do it be exploding the string to values and then compare, but I think it will be slow. what about preg_replace() will it be faster? Any one did it using this function?
The shortest code would be:
$str = implode(',',array_unique(explode(',', $str)));
If it is the fastest... I don't know, it is probably faster then looping explicitly.
Reference: implode, array_unique, explode
Dealing with: $string = 'one,two,one,five,seven,bag,tea';
If you are generating the string at any point "up script", then you should be eliminating duplicates as they occur.
Let's say you are using concatenation to generate your string like:
$string='';
foreach($data as $value){
$string.=(strlen($string)?',':'').some_func($value);
}
...then you would need to extract unique values from $string based on the delimiter (comma), then re-implode with the delimiter.
I suggest that you design a more direct method and deny duplicates inside of the initial foreach loop, like this:
foreach($data as $value){
$return_value=some_func($value); // cache the returned value so you don't call the function twice
$array[$return_value]=$return_value; // store the return value in a temporary array using the function's return value as both the key and value in the array.
}
$string=implode(',',$array); // clean: no duplicates, no trailing commas
This works because duplicate values are never permitted to exist. All subsequent occurrences will be used to overwrite the earlier occurrence. This function-less filter works because arrays may not have two identical keys in the same array(level).
Alternatively, you can avoid "overwriting" array data in the loop, by calling if(!isset($array[$return_value])){$array[$return_value]=$return_value;} but the difference means calling the isset() function on every iteration. The advantage of using these associative key assignments is that the process avoids using in_array() which is slower than isset().
All that said, if you are extracting a column of data from a 2-dimensional array like:
$string='';
foreach($data as $value){
$string.=(strlen($string)?',':'').$value['word'];
}
Then you could leverage the magic of array_column() without a loop like this:
echo implode(',',array_column($str,'word','word'));
And finally, for those interested in micro-optimization, I'll note that the single call of array_unique() is actually slower than a few two-function methods. Read here for more details.
The bottomline is, there are many ways to perform this task. explode->unique->implode may be the most concise method in some cases if you aren't generating the delimited string, but it is not likely to be the most direct or fastest method. Choose for yourself what is best for your task.

multidimensional array

Please explain what is the meaning of
foreach ($toplist['children'] as $subkey => $subname)
and where the children come from. I'm confused.
Basically $toplist is an array of values. One of those values has been called 'children'.
In this case, the value at position 'children' is itself an array.
Your line of code is telling the computer to loop over each of the values inside the 'children' array and extract the key and value.
$subkey is the key, $subname is the name.
In other words, $toplist['children'][$subkey] == $subvalue
The other elements are coming from the $toplist['children'] array which you got to figure out where it is coming from since you have not put in all the needed code for the question. See this about foreach machenism to learn more about it.
his simply gives an easy way to
iterate over arrays. foreach works
only on arrays, and will issue an
error when you try to use it on a
variable with a different data type or
an uninitialized variable.
php.net

Categories