0

I have a form that is taking user input and placing it into an array. Each form item has a label. The text in the labels corresponds to the items in the array $items.

if(isset($_POST['submit'])){

$items = array('Apple', 'Banana', 'Oranges', 'Grapes');    
$amount = array();    
foreach($_POST['item'] as $value){    
    $amount[]=($value);
}
  $total =array_combine($items, $amount);
    }
?>
<form method="post" action"">
<label>Apple</label><input type="text" name=item[]>
<label>Banana</label><input type="text" name=item[]>    
<label>Orange</label><input type="text" name=item[]>
<label>Grapes</label><input type="text" name=item[]>

<input type="submit" name="submit" value="submit">    
</form>


<?php
print_r($total);
?>

I combine both arrays and get the output as the numbers represent the amount of items. Array ( [Apple] => 12 [Banana] => 14 [Oranges] => 7 [Grapes] => 2 )

I want to be able to skip an item in the array if one of the forms is not filled in for example if oranges is missed out. I would like the array to output

Array ( [Apple] => 12 [Banana] => 14 [Grapes] => 2 )

I also tried imploding $total to output the array items

echo implode(",", $total);

However I only go the values from the $amount array and not both $items and $amount.

1 Answer 1

1

If the code structure should stay same and you need to add some lines of code, you could just add the counter and if statement in foreach loop like this:

if(isset($_POST['submit'])){

$items = array('Apple', 'Banana', 'Oranges', 'Grapes');  
$amount = array();   
$counter=0; 
foreach($_POST['item'] as $value){ 
    if(strlen($value) != 0) {
        $amount[]=($value);
    }
    else{
        unset($items[$counter]);
    }
    $counter++;
}
  $total =array_combine($items, $amount);
}

This will keep the count of items you have in $items array and if there is no value in the passed data, the if statement will filter that item out from $items array.

In this case you also should check if the passed data from the form is not empty, otherwise PHP will throw you an error.

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.