Delirium tremens
Delirium tremens

Reputation: 4739

validation with variable variables not working

$method = 'post';

$method = strtoupper($method);
echo $method.'test1';

$method = '_'.$method;
echo $method.'test2';

$method = $$method;
echo $method.'test3';

Why doesn't this print the content of $_POST between 2 and 3?

Upvotes: 0

Views: 158

Answers (2)

Jonathan Fingland
Jonathan Fingland

Reputation: 57167

In addition to John Kugelman's excellent point, I would use the following

$method = $_POST;

echo $method['test1'];

echo $method['test2'];

echo $method['test3'];

and not bother with trying to access a contant array name via a string

If you really insist on using a string to access these, you could

$method = "post";
$method = strtoupper($method."_");    
if (isset(${$method})) {
  $method = ${$method};

  echo $method['test1'];

  echo $method['test2'];

  echo $method['test3'];
}

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361739

You want $method['test3'] to access the elements of the $_POST array. The dot . operator does string concatenation. Square brackets [] are used for array access.

Upvotes: 1

Related Questions