0

Didn't know how to specify question to be more specific and more meaningful.

Basically I've a Customer information module with ability for adding multiple contacts for each customer and it will something like that:

<p>Contacts</p>
<ul>
<li>
<label for="name">Name: <label><input type="text" name="name[]" value="" />
<label for="lname">Last Name: <label><input type="text" name="lname[]" value="" />
<label for="phone">Phone: <label><input type="text" name="phone[]" value="" />
</li>
<li>
<label for="name">Name: <label><input type="text" name="name[]" value="" />
<label for="lname">Last Name: <label><input type="text" name="lname[]" value="" />
<label for="phone">Phone: <label><input type="text" name="phone[]" value="" />
</li>
<li>
<label for="name">Name: <label><input type="text" name="name[]" value="" />
<label for="lname">Last Name: <label><input type="text" name="lname[]" value="" />
<label for="phone">Phone: <label><input type="text" name="phone[]" value="" />
</li>
</ul>

This is a rough example to show you idea. When that form is submitted to php script, and for example last name in second contact details is blank, I'm getting offset error when I'm trying to loop through all contact like that?

<?php

$total = count($_POST['name']);
$name = $_POST['name'];
$lname = $_POST['lname'];
$phone = $_POST['phone']
for($x = 0 ; $x > $total; $x)
{
    echo 'Name: '.$name[$x].' Last name: '.$lname[$x].' Phone: '.$phone[$x];
}

?>

I didn't test this particular snippet, it is here only to show you idea( probably few of you had similar issue).

3
  • 1
    try $name = $_POST['name'] ? $_POST['name'] : ''; or $name = $_POST['name'] == '' ? '' : $_POST['name']; Commented Nov 26, 2012 at 9:50
  • I use a combination of isset and empty to ensure that the item exists and that it has a value. In some cases, empty will not work as you will want to receive 0, '', or false as a valid value. In which case you would need to apply a little more validation. Commented Nov 26, 2012 at 9:52
  • Will remember your advice guys, thanks Commented Nov 26, 2012 at 10:06

1 Answer 1

2
for($x = 0 ; $x < $total; $x++)
{
    if(!empty($name[$x]))
    echo 'Name: '.$name[$x];
}

Is this what you are looking for?

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

1 Comment

thanks harry, this should do the trick. I was thinking about this solution but I'm afraid that performance will be affected as in some cases I will need have over 30 iterations with about 10 records to check in each iteration. Will give a shot to empty and we will see what happen

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.