Jump to content

Simple Loop into array


jarvis
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

Link to comment
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>
Link to comment
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
  • Like 1
Link to comment
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.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.