简体   繁体   中英

Add a key in array even value is empty PHP

I have a form in which can be a few lines of inputs the same a few times, like this,

<input type="text" name="company[]"><input type="text" name="type[]">
<input type="text" name="company[]"><input type="text" name="type[]">
<input type="text" name="company[]"><input type="text" name="type[]">

Now I have to input these fields to the database, so I looped through the the input fields and it works fine.

But I have one problem: sometimes the fields in the loop can be empty. Ie the company will have a value but not the type. So how can I make so that the loop should output the empty value in a key like this:

Array(
   company => array(
          [0] => string0
          [1] => string1
          [2] => string2
     )
   type => array(
          [0] => 
          [1] => string1
          [2] => string2
     )
)

So you can see that first key of type is empty, so how can I achieve that,

I'm trying to do this but no result,

$postFields = array('company', 'type');
$postArray = array();
foreach($postFields as $postVal){
    if($postVal == ''){
        $postArray[$postVal] = '';
    }
    else {
        $postArray[$postVal] = $_POST[$postVal];
    }
}

Appreciate any help,

This HTML:

<input type="text" name="company[]"><input type="text" name="type[]">

Will dynamically populate the keys of your array. I think you will never get an empty 0 element, as long as one of the text fields was submitted. Instead, you'd end up with mismatching lengths of arrays, which you won't be able to determine which number was omitted.

The solution is to explicitly state the keys in the HTML, like so:

<input type="text" name="company[0]"><input type="text" name="type[0]">
<input type="text" name="company[1]"><input type="text" name="type[1]">
<input type="text" name="company[2]"><input type="text" name="type[2]">

Now, you can loop over the arrays and if a certain key isn't set, you can set it to an empty string:

foreach( range( 0, 2) as $i) {
    if( !isset( $_POST['company'][$i]))
        $_POST['company'][$i] = "";

    if( !isset( $_POST['type'][$i]))
        $_POST['type'][$i] = "";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM