-1

I want to use $array['parameter'] where parameter is taken from post array or is set previously, though php won't allow that? Why it can't be used like in string statements

$string = "This is my parameter $parameter";
MWiesner
  • 8,868
  • 11
  • 36
  • 70
Goking
  • 61
  • 1
  • 1
  • 8
  • 4
    Could you show some more of your actual code? Not quite sure what you're asking –  Dec 26 '15 at 21:16

2 Answers2

1

If 'parameter' is a key in your post array, you can access it with:

$_POST['parameter']

Thus, you can do:

$parameter = $_POST['parameter'];
$string = "This is my parameter $parameter";

Or, just for your own edification, you can extract all (key, value) pairs of an array into variables. Since $_POST is an array, you can use the extract() function on it. However, using extract() comes with inherent risks. If you choose to go this route, be sure you have a great reason for using extract() -- odds are, any reason you can think of isn't great enough (Further reading: What is so wrong with extract()?).

//We expect 'parameter' to be a key in the $_POST array.
extract($_POST);
if(isset($parameter)) {
    $string = "This is my parameter $parameter";
}

http://php.net/manual/en/function.extract.php

As always, be sure to sanitize your input: The ultimate clean/secure function

Community
  • 1
  • 1
Tim
  • 485
  • 2
  • 9
  • 1
    @Terminus, I debated adding that snippet, as well. I erred on the side of "more knowledge is better" but perhaps I should have added a disclaimer. I've updated the answer. – Tim Dec 27 '15 at 07:02
0

to use $array['parameter'] where parameter is taken from post array or is set previously, though php won't allow that? Why it can't be used like in string statements

So I'll take a stab at this since you've added some code. If you want to access an element in an array based on the value of a variable you simply

$array[$value]

If you want to use a value held by the $_POST array to act as the key you

$array[$_POST['parameter']]

If you only want to do that if the value is set in $_POST

if (isset($_POST['parameter']))
  // use the value here as before

Now, if you just want to stick a value from an array into a string without using the . concatenation operator, wrap it in curly braces like so:

$string = "This is my parameter {$array['parameter']}

Be careful when using user input for anything. @Tim had a link to a good answer on that: sanitize input

Community
  • 1
  • 1