0

I have these arrays and i want to loop through every array by creating a dynamic variable that put their name in foreach loop automatically something like this

foreach ($activities.$i as &$activity) { //$i = 1,2,3,4..
   //code

}

//activities
$activities1 = $_POST["activities1"];
$activities2 = $_POST["activities2"];
$activities3 = $_POST["activities3"];
$activities4 = $_POST["activities4"];

1 Answer 1

1

Easier method is to simply use the array naming hack:

<input name="activities[1]" ..>
<input name="activities[2]" ..>
<input name="activities[3]" ..>

which makes $_POST['activities'] you array:

foreach($_POST['activities'] as $i => $value) {
   // $i -> 1,2,3,4
}

But if you insist on embedding the index inside the key's name, then:

foreach(range(1,4) as $i) {
    foreach($_POST["activities{$i}"] as $value) {
        ...
    }
}
Sign up to request clarification or add additional context in comments.

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.