0
$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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

No, I want $_SESSION, $_COOKIE, $_POST and $_GET from 'session', 'cookie', 'post' and 'get'.
I think I'm going to end up using if($method == 'post') $method = $_POST; if($method == 'get') $method = $_GET; if($method == 'session') $method = $_SESSION; if($method == 'cookie') $method = $_COOKIE;
1

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'];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.