Home > database >  PHP How to foreach explode POST multiple values
PHP How to foreach explode POST multiple values

Time:02-02

I want to foreach explode from POST multiple values

Cut off "1234" with first space (by character not position)

I get error "Array to string conversion"

Form

<input type="checkbox" name="docid[]" value="1234 harry potter">

Submit

$docID = $_POST['docid'];
foreach($docID as $val) {
    echo explode(' ', $val);
}

Output

1234

EDIT I want to insert output to DB

CodePudding user response:

explode returns an array of strings, so echo won't work. It also has a third parameter, use that to limit the elements returned:

<?php 
$docID = $_POST['docid'];
foreach($docID as $val) {
    $exploded = explode(' ', $val, 2);
    // print_r($exploded); # Array ( [0] => 1234 [1] => harry potter )
    echo $exploded[0];
}

will output 1234

Edit: if you want to cut off 1234 from your result use echo $exploded[1]; - this will output harry potter

CodePudding user response:

I'm not quite sure what you're trying to do but based on your code, if you just want to log what you are getting from your explode, simply encapsulate your explode in print_r()

e.g:

foreach($docID as $val) {
    print_r(explode(' ', $val));
}

CodePudding user response:

Easy:

<form action="index.php" method="post">
    <input type="checkbox" name="docid[]" value="1234 harry potter">
    <input type="checkbox" name="docid[]" value="45678 test 123">
    <button type="submit">Submit</button>
</form>
<?php

$docID = $_POST['docid'] ?? [];

foreach ($docID as $val) {
    $values = explode(' ', $val);

    foreach ($values as $v) {
        echo $v . PHP_EOL;
    }
}

Output (if all checkboxes are checked):

1234 harry potter 45678 test 123

CodePudding user response:

I found another solution, It work too.

$docID = $_POST['docid']

foreach($docID  as $val) {
    echo explode(' ', $val)[0];
    echo '<br>';
}
  •  Tags:  
  • Related