0

my post array is as follows

array(106) {  
    ["service1"] => string(2) "No" 
    ["in_house1"]=> string(2) "in"  
    ["service2"]=>  string(2) "No"  
    ["in_house2"]=> string(2) "in"  
    ["service3"]=>  string(2) "No"  
    ["in_house3"]=> string(2) "in" 
    ...
}

I want to insert these values using a While loop. How should I split array variables ?

eg: I want ["service1"] to be split as service.$i

Can you please suggest any solution.

Namrata Shrivas
  • 77
  • 2
  • 13

3 Answers3

2

It seems there is no simple shortcut for this.. You may simply do a loop

$service=array();
for ($i=1;isSet($_POST["service".$i]);$i++)
    $service[$i] = $_POST["service".$i];
AndreyS Scherbakov
  • 2,674
  • 2
  • 20
  • 27
0

As @FirstOne said, your question is a bit unclear. But I am gonna make an attempt on interpreting it using your Questions tags.

I think you are looking for the answer that is posted for this question: How to loop through an associative array and get the key?

So to re-write that answers code to your case:

foreach ($arr as $key => $value) {
    echo "Item: " . $key . " Status:" . $value;
}

To just loop through the array that you get by post and write the items name and status/value. So inside the foreach you can choose to do whatever you want with the keys and values of the associative array.

So to split these up like you wanted to, one might use regexp patterns to get the name and the digit separately from the item name, and then assign the value to a variable or separate array based on that.

Morten Hekkvang
  • 356
  • 2
  • 7
0

I think you missed something in your HTML form format. Because what you are trying to do is send HTML "array" data.

You can do so, by adding [] as suffix in your input name.

<input type="checkbox" name="services[]" value="1" />
<input type="checkbox" name="services[]" value="2" />

Then, you can retrieve your POST array with :

<?php
foreach($_POST['services'] as $service){
  echo $service;
}
Yoann
  • 76
  • 3