# Simple Loop into array

Go to solution Solved by Barand,

## Recommended Posts

Hi All

I hope someone can help. I know it's easy but for some reason, I simply can't get my head around it.

I need to collect values from a form:

```\$gallery_1 = \$_POST['item_meta'][124];
\$gallery_2 = \$_POST['item_meta'][125];
```

I have up to 10 of the above.

I'm then using:

```\$meta_value=\$gallery_1.','.\$gallery_2....;
And so on to \$gallery_10
```

However, this isn't efficient I'm sure and what happens if the 2nd or 8th - 10th input is empty

Can I put this into a foreach loop to build up an array of values?

Thanks

##### Share on other sites

well it's already an array of values, what exactly are you sending through as \$_POST['item_meta'] and why does it go over 125 for what you say could go up to 10?

##### Share on other sites

Hi Muddy_Funster

the 125 is the input field name (generated by form code beyond my remit), so the 10 fields would be 124,125...133

I guess I was just wondering if there was a tidier way of coding it rather than what I've gone with

Thanks

##### Share on other sites

You could loop through \$_POST['item_meta']. Here's a quick example:

```<?php
//IF FORM WAS SUBMITTED
if(\$_SERVER['REQUEST_METHOD'] == 'POST') {
foreach(\$_POST['item_meta'] as \$currIndex => \$currValue) {
print "<div>\$currIndex = \$currValue</div>";
}
}
?>
<form method="post">
<input type="text" name="item_meta[124]" />
<input type="text" name="item_meta[125]" />
<input type="text" name="item_meta[128]" />
<input type="text" name="item_meta[132]" />
<input type="submit" name="submit" value="Save" />
</form>```
##### Share on other sites

• Solution

Supposing you have, this (where you said some could be empty)

```\$_POST['item_meta'][124] = 'aaa';
\$_POST['item_meta'][125] = 'bbb';
\$_POST['item_meta'][126] = 'ccc';
\$_POST['item_meta'][127] = 'ddd';
\$_POST['item_meta'][128] = 'eee';
\$_POST['item_meta'][129] = '';
\$_POST['item_meta'][130] = 'fff';
\$_POST['item_meta'][131] = '';
\$_POST['item_meta'][132] = '';
\$_POST['item_meta'][133] = 'ggg';

```

then to get the \$meta_value, all you need is

```\$meta_value = join(',', array_filter(\$_POST['item_meta']));
```

to check

```echo \$meta_value;         //-->  aaa,bbb,ccc,ddd,eee,fff,ggg
```
##### Share on other sites

Thanks Barand. that's more the sort of thing I was after

##### Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

×   Pasted as rich text.   Restore formatting

Only 75 emoji are allowed.