Home > database >  GET input as PHP array
GET input as PHP array

Time:11-02

I have my HTML input as

<input type="number" name="no_pi" id="no_pi" class="form-control" placeholder="Number of Pieces">

and other two inputs as

<input type="number" name="ht" id="ht" placeholder="Height of Package" class="form-control">
<input type="number" name="bd" id="bd" placeholder="Breadth of Package" class="form-control">

I want to user input 3 in number of pieces field, then input 20, 20, 30 in weight and 10, 10, 20 in breadth fields.

PHP will then do calculations with every 20, 10 and then next pair and so on x number of times as assigned in the number of pieces field.

PS: Array defined above is example if user input 5 in number of pieces then both arrays should be of 5 values and PHP will do calculations of those 5 pairs.

Any idea how to achieve this

CodePudding user response:

You can use explode and array_map to achieve this.

function inputToArray(string $string)
{
    $string = preg_replace('/\s /', '', $string);
    $string = trim($string, ",");
    $array = array_map('intval', explode(',', $string));
    return $array;
}

$no_of_pieces = (int)$_POST['no_pi'];
$ht = $_POST['ht']; //make sure it is in format 1,2,3,4,.....
$ht = inputToArray($ht); //array(20,30,10)
$bd = $_POST['bd']; //make sure it is in format 1,2,3,4,.....
$bd = inputToArray($bd); // array(10,20,30)

if ((count($ht) === count($bd)) && (count($bd) === $no_of_pieces)) {
    for ($piece = 0; $piece < $no_of_pieces; $piece  ) {
        $areaOfPiece = $ht[$piece] * $bd[$piece];
        echo $areaOfPiece;
    }
} else {
    echo "Number of inputs does not match";
}
  • Related