0

Hey all i just want to make sure i am adding the value correctly to my array varable:

$post_values = array(
"x_first_name"      => $_POST['first_name'],
"x_last_name"       => $_POST['last_name']
);

If anyone could confirm that its the way it needs to be then please do :o)

David

3
  • 3
    You can check this yourself here: http://php.net/manual/en/language.types.array.php Commented Feb 4, 2012 at 15:13
  • 1
    Looks okay to me, but like @tbraun89 said. Double check it with the link he provided. Commented Feb 4, 2012 at 15:16
  • @ThinkingMonkey, Eric Wutchin: Thanks! :o) Commented Feb 4, 2012 at 15:18

2 Answers 2

2

That works, but these also work:

$post_values = array();
$post_values['x_first_name'] = $_POST['first_name'];

$post_values = array();
array_push($post_values, $_POST['first_name'];
// but now you don't have the desired index, just numeric indexes

You might also first want to check whether the post value exists:

if (isset($_POST['first_name']) {
    $post_values['x_first_name'] = $_POST['first_name'];
}
Sign up to request clarification or add additional context in comments.

2 Comments

tbraun89's tip is also good, the php.net website has a lot of examples.
It would be if it showed an example of what i was looking for "XXXX" => $POST['XXXX'],
-1

you could also do

$post_values = array();
foreach ($_POST as $k => $v) {
   $post_values['x_' . $k] = $v;
}

and please do validate POST inputs!

$post_values['x_' . htmlentities($k, ENT_QUOTES)] = htmlentities($v, ENT_QUOTES);

3 Comments

Using htmlentities here is wrong. You should not use it to validate data (the function does not even validate anything!), but you have to use it to escape data in the correct context. htmlentities does not help anything when working with a database, json, csv, links, etc.
"Validate" is maybe a wrong term but htmlentities prevents malicious code from being injected. Which, to my knowledge, is never wrong to try and prevent
No, it only prevents malicious code from being injected into html documents. Variables themselves are not in html context until echoed. You don't get any benefit from it when you use the variable in another context (csv, json, databases …)

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.