简体   繁体   中英

PHP Get Array key with Value

I am trying to get the array key of every input type that has value.

Please see below my code

<form action="welcome.php" method="post">
<input type="text" name="ptotal_monthly_fee[]" >
<input type="text" name="ptotal_monthly_fee[]" value"1">
<input type="text" name="ptotal_monthly_fee[]" >
<input type="text" name="ptotal_monthly_fee[]" value"2">
<input type="text" name="ptotal_monthly_fee[]" >
<input type="submit">

</form>

This is welcome.php

<?php

$count = array_keys($_POST['ptotal_monthly_fee']);

foreach ($count as $value) {
  echo "$value <br>";
}
?>

My Output is: 0 1 2 3 4

I want my output to be: 1 3

You need to check the values in the posted array and then echo the corresponding key if the value is not empty:

foreach ($_POST['ptotal_monthly_fee'] as $key => $value) {
    if (!empty($value)) echo "$key <br>";
}
$stmt = '';
if(isset($_POST['ptotal_monthly_fee'])){
  foreach($_POST['ptotal_monthly_fee'] as $key => $value){
    if($value !== ''){
      $stmt .= "Key: $key<br>";
    }    
  }
}

Echo out $stmt in html

<?=$stmt?>

NOTE: in your code your value is not set in your inputs. Should be value="1" / value="3"

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