uno
uno

Reputation: 867

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

Upvotes: 0

Views: 47

Answers (2)

dale landry
dale landry

Reputation: 8600

$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"

Upvotes: 1

Nick
Nick

Reputation: 147146

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>";
}

Upvotes: 4

Related Questions