Forum Moderators: coopster

Message Too Old, No Replies

Use $_POST['id'] and $_GET['id'] as variable directly?

         

iProgram

6:24 am on Nov 23, 2004 (gmt 0)

10+ Year Member



I used to use $_POST['id'] as a variable directly. Each time I need to use a POST data, I will use $_POST['data_name'] to reference them, for example:

echo $_POST['id'];
for ($i=0; $i< $_POST['id']; $i++)
...
But is it a good idea to store POST/GET data to a variable first? For example:
$id=$_POST['id'];
echo $id;
for ($i=0; $i< $id; $i++)

?

IanKelley

8:06 am on Nov 23, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



People do that to make coding easier. $id is easier to type :-)

bloke in a box

9:21 am on Nov 23, 2004 (gmt 0)

10+ Year Member



Agreed, I always use $varName = $_POST['var'] because it makes the code easier to read and looks neater.

coopster

3:18 pm on Nov 23, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



The only issue with this practice is that you are assuming the variable will exist. It may not, depending on how you code your form. This is why you often see the use of isset() [php.net] to determine the existence before populating the variable, otherwise give it a default value.
$variable = (isset($_POST['variable'])) ? $_POST['variable'] : '';

iProgram

8:42 am on Nov 24, 2004 (gmt 0)

10+ Year Member



I asked this question because someone said that each time you use $_POST['something'], php will always lookup 'something' in the whole POST data queue. So it's better to assign a value to a POST data. Isn't it?

IanKelley

9:45 am on Nov 24, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Everything is in memory and all the variables are mapped. It probably takes longer to assign the value to a new variable unless you're accessing the array 100's of times.

Either way it's not enough CPU time to make a noticeable difference.

Remember also that the $_POST array is automatically global.