Page 1 of 1

Can anyone tell me what the problem with this is ? (forech)

Posted: Wed Mar 03, 2004 5:59 pm
by RecoilUK
Hi

I have the following code....

Code: Select all

$postvars = array('housetype','gardentype','parkingtype');
$submittedposts = "";
$submittedvar = "";

function postvars($arg) {
	$$arg = $_POSTї$arg];
}

foreach($postvars as $value) {
	postvars($value);
	if (!empty($_POSTї$value])) {
		$submittedposts++;
	}
}
but whenever its run, it complains about an undefined index on each of the variables i,m trying to make.

Any idea,s?

Thx guys

Posted: Wed Mar 03, 2004 6:06 pm
by markl999
If you're just trying to check if all the values in the postvars array were posted, then i'd do it like this.

Code: Select all

<?php
$postvars = array('housetype','gardentype','parkingtype');
foreach($postvars as $value){
  if(empty($_POST[$value])){
    $missing[] = $value;
  }
}
if(!empty($missing)){
  echo 'Missing post vars';
  var_dump($missing);
} else {
  echo 'All posted ok';
}

?>

Posted: Wed Mar 03, 2004 6:10 pm
by RecoilUK
Hi

Yes I am checking that, but also I want to make a variable, named from the value of each postvars array value.

So , I have a housetype value in postvars array, I also want a normal variable ....

$housetype

that has the same value as $_POST['housetype']

Thx

Posted: Wed Mar 03, 2004 6:14 pm
by markl999
http://php.net/extract

So extract($_POST); will make $housetype, $gardentype etc..etc.. you could put the extract after you've checked there are non missing.

Posted: Wed Mar 03, 2004 8:07 pm
by McGruff
Be careful with extracting $_POST. You cannot assume user input is what you think it will be: alien keys will overwrite legitimate vars in the same scope as the extract line. Use the prefix option if you must use extract.

Posted: Wed Mar 03, 2004 9:23 pm
by RecoilUK
Hi

To be honest i,d rather not use extract at all.

I think ...

Code: Select all

$$var = $var
should create a variable based on the value of another variable.

However, I cant use this in a foreach loop, because it would seem, any vars have to be already initiated.

Anyway around this?

Thx

Posted: Wed Mar 03, 2004 9:30 pm
by markl999
This test works ok for me.

Code: Select all

<?php
error_reporting(E_ALL);
if(!empty($_POST)){
  $postvars = array('housetype','gardentype','parkingtype');
  foreach($postvars as $value){
    if(empty($_POST[$value])){
      $missing[] = $value;
    } else {
      $$value = $_POST[$value];
    }
  }
  if(!empty($missing)){
    echo 'Missing post vars';
    var_dump($missing);
  } else {
    echo 'All posted ok<br />';
    echo $housetype, $gardentype, $parkingtype;
  }
}

?>
<form method="post" action="">
<input type="text" name="housetype" value="">
<br />
<input type="text" name="gardentype" value="">
<br />
<input type="text" name="parkingtype" value="">
<br />
<input type="submit" value="submit" name="submit">
</form>