Generally to get the values from fields or any element in php from any input elements, textarea and so on we use either $_GET or $_POST and here I am not going into the intricacies of these methods you can refer to
PHP Method on Getting Values From Form
Lets say that we have following view result after adding the fields dynamically using JQuery from our Previous Post
HTML Markup
<form method="post"> <div style="padding:10px;"> <div> <button class="add_field_button">Add More Fields</button> <input type="submit" value="get" name="get"></div> <input type="text" name="char[]" required="required"> <div class="input_fields_wrap">
<div><input type="text" name="char[]" required="required"><a href="#" class="remove_field"><span><i class="fa fa-remove"></i></span></a></div>
<div><input type="text" name="char[]" required="required"><a href="#" class="remove_field"><span><i class="fa fa-remove"></i></span></a></div>
<div><input type="text" name="char[]" required="required"><a href="#" class="remove_field"><span><i class="fa fa-remove"></i></span></a></div>
<div><input type="text" name="char[]" required="required"><a href="#" class="remove_field"><span><i class="fa fa-remove"></i></span></a></div>
</div>
</div>
</form>
So here we have a form with post method so will be using $_POST method and also we have an array of name char as char[].
Now as it’s an array, in PHP we have got further more options to interact with arrays, we can always get the array values directly from $_POST and its array index number.
PHP Code
<?php $_POST[char][0] $_POST[char][1] $_POST[char][2] $_POST[char][3] $_POST[char][4] ?>
the problem is that there is chance of encountering an undefined variable/index error if the particular field doesn’t exist.
There’s an better option the mighty implode() function , through which arrays values can be obtained as a string separated by commas or using any such predefined separator.
implode() function
<?php if($_POST){ $var = implode("," , $_POST['char']); echo $var; } ?>
There’s also a way to get those value through a loop lets see foreach() loop according to markup .
foreach() loop
<?php if(isset($_POST['get'])){ if(isset($_POST['char'])){ foreach($_POST['char'] as $t){ echo $t."<br/>"; }}} ?>
That’s all for now, let me know if you find and problem in getting the value.
Leave a Reply