How do i validate that two arrays have entries in the same place?

Hi i wonder if anyone can help.

i have a form where i want a user to submit one or more url/links and there descriptive titles.

The url/links field is

<label for="link">Link</label>
<input type="text" name="links[]" id="link" />

The title field is

<label for="title">Title</label>
<input type="text" name="links[]" id="title" />

I have programmed some jquery so that when an ‘add another link’ link is clicked another link/title appeared field appears. i can’t know how many url/titles are needed in advance. So if a user clicked ‘add another link’ twice the code would be

<label for="link">Link</label>
<input type="text" name="links[]" id="link" />

<label for="title">Title</label>
<input type="text" name="titles[]" id="title" />


<label for="link2">Link</label>
<input type="text" name="links[]" id="link2" />

<label for="title2">Title</label>
<input type="text" name="titles[]" id="title2" />

<label for="link3">Link</label>
<input type="text" name="links[]" id="link3" />

<label for="title3">Title</label>
<input type="text" name="titles[]" id="title3" />

So far so good. When the entries get submitted I have two arrays which i can
use a ‘for loop’ to loop through - these variables

$_POST['links']
$_POST['titles']

The problem is I want to validate that for every link there is a title and every title there is a link, so if

$_POST['links'] // array entry for 1,3,6
$_POST['links'] // array entry for 1,3,6

Then valid

But if

$_POST['links'] // array entry for 1,3,6
$_POST['titles'] // array entry for 2,4,7

Then invalid show error message.

Then i will remove all empty array items and submit to a database. Can anyone explain how to do this?

Thanks for your help.

Steven

The “official” term for them is parallel arrays: http://en.wikipedia.org/wiki/Parallel_array

That works brilliantly - thanks for your help!

I call these ‘aligned’ arrays. I don’t know if anyone else uses that term, but it’s how I think of them. The values in the same position of each array align.

So you can loop like this:


$links = array_map('trim', $_POST['links']);
$titles = array_map('trim', $_POST['titles']);

$len = count($links);
for($i=0; $i < $len; $i++) {

   //both fields blank, skip
   if(!$links[$i] AND !$titles[$i]) {
      continue;
   }

   //missing URL
   if(!$links[$i]) {
      echo 'A URL is required for link ' . $i+1;
   }

   //missing title
   else if(!$titles[$i]) {
      echo 'A title is required for link ' . $i+1;
   }
}