Solu vector input

De wikiserver
Dreceres ràpides: navegació, cerca

//index.php //primera solución

<?php
  if( isset($_POST["vec"])) 
  {
  	print_r($_POST["vec"]);
 
  	$vector= $_POST["vec"];
  	$sum =0;
  	print_r(count($vector));
   for ($j=0; $j <count($vector) ; $j++) { 
   	$sum+=$vector[$j];

   }
   
   echo "<br>";
   echo $sum;
  }
?>
<html>
<body>
  <form action="<?php $_PHP_SELF ?>" method="POST">   

<?php
for ($i=0; $i < 10 ; $i++) { 
	echo $i;
	echo "<input type='text' name='vec[]' size='10'>";
	echo "<br>";
}
?>
  <input type="submit" />
  </form>
</body>
</html>

//Otra solución //index.php

<html>
<body>
<form action="suma.php" method="POST">

    <?php
    for ($i=0; $i < 10 ; $i++) {
        echo "ho".$i;
        //echo "<input type='text' name='vec[]' size='10'>";
        echo "<input type='text' name='vec$i' size='10'>";
        echo "<br>";
    }
    ?>
    <input type="submit" />
</form>
</body>
</html>

//fichero suma.php

<?php

print_r($_POST);

$vector= $_POST;
$sum =0;

for ($j=0; $j <count($vector) ; $j++) {
     $sum+=$vector['vec'.$j];

}

/* //altra forma de recorrer
foreach($vector as $valor){
    $sum+=$valor;
}
*/

echo "<br>";
echo $sum;

?>