0

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

2 Answers 2

4

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>"; } 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.