How can you pass a variable as the $_POST array key value in PHP? Or is it not possible?
$test = "test";
echo $_POST[$test];
Thanks
PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables. The example below shows a form with an input field and a submit button.
The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.
The $_REQUEST variable The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.
The $_POST variable collects the data from the HTML form via the POST method. When a user fills the data in a PHP form and submits the data that is sent can be collected with the _POST Method in PHP. The Post Method transfers the information via the Headers.
If I get you right, you want to pass a variable from one php-file to another via post. This sure is possible in several ways.
1. With an HTML-form
<form action="target.php" method="post">
  <input type="text" name="key" value="foo" />
  <input type="submit" value="submit" />
</form>
if you click on the submit-button, $_POST['key'] in target.php will contain 'foo'.
2. Directly from PHP
$context = stream_context_create(array(
    'http' => array(
      'method'  => 'POST',
      'header'  => "Content-type: text/html\r\n",
      'content' => http_build_query(array('key' => 'foo'))
    ),
  ));
$return = file_get_contents('target.php', false, $context); 
Same thing as in 1., and $return will contain all the output produced by target.php.
3. Via AJAX (jQuery (JavaScript))
<script>
$.post('target.php', {key: 'foo'}, function(data) {
  alert(data);
});
</script>
Same thing as in 2., but now data contains the output from target.php.
$_POST['key'] = "foo";
echo $_POST['key'];
If I understood right, you want to set a $_POST key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With