1

I'm trying to set a variable equal to one of the sub-arrays of my $_POST variable.

$array[] = $_POST['contact-info'];
echo $array['email'];

It won't work though as it echoes NULL.

Any suggestions?

1
  • 1
    show print_r($_POST) Commented Jun 25, 2013 at 21:56

4 Answers 4

1

You don't need square brackets for assigning this sub-array to a variable.

$array = $_POST['contact-info'];
echo $array['email'];
Sign up to request clarification or add additional context in comments.

7 Comments

did you use print_r($_POST);?
in that case print_r($_POST) its not what you think it is
I could echo $_POST['contact-info']['email']; but I'm looking for a way to simplify the $_POST variable down to it's subcomponent arrays.
@MrGrinst yes, do print_r($_POST); and paste it's result here.
Array ( [contact-info] => Array ( ['name'] => Array ( ['first'] => ['middle'] => ['last'] => ) ['email'] => ['phone'] => ['address'] => Array ( ['street'] => ['po'] => ['city'] => ['state'] => ['zip'] => ) ) )
|
0

$_POST simply is not a multi dimensional array. echo print_r($_POST,1); will show you what is exactly in $_POST. When used, $_POST will always be populated for you by PHP with key (string) - value (string) pairs. If $_POST does contain sub arrays, then it's probably populated by you yourself or by some framework you are using.

For now I'm guessing that contact-info is the form name of the form you are submitting. The form name is not of importance when reading out the submitted form. You can directly access the sent data through the name of the field sent..

For example, if you had:

<form name="contact-info" action="yourscript.php" method="post">
  Please enter your e-mail address:<br/>
  <input name="email" type="text" value="" />
</form>

Then in your php script you should have:

<?php
  echo "You just entered: " . $_POST['email']; 
?>

Comments

0

$array['email'] is never set. You set the array like this:

$array[] = $_POST['contact-info'];

So assuming that was the first time you've used $array then you would access email by:

echo $array[0]['email'];

If you don't need $array to be multi-dimensional, You could always just do:

$array = $_POST['contact-info'];
echo $array['email'];

Comments

0

As mentioned elsewhere, the email is currently empty. The structure of the array should match the form so, if your form is

name="contact-info[email]"

Then in PHP you would access that as

$contact_info = $_POST['contact-info'];
$email = $contact_info['email'];

OR

$email = $_POST['contact-info']['email'];

Also, try this for a little more clarity when debugging an array, it makes spoting the associations easier.

<pre>
<?php print_r($_POST);?>
</pre>

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.