I have a multi-select form feeding from database, if I implode it with comma separated, I will get values like item1,item2,item3. However, I only want to get the last selected item which is item3 in d case above. I also tried to explode to split it but didn't work out
this is my code below
<select multiple="multiple" name="enrolledterm[]" style="width: 100%;" data-toggle="select2" data-placeholder="Select Terms.." data-allow-clear="true" required="required">
<option value="<?php echo $term_one_date ?>">Winter Term ends on <?php echo $term_one_date ?></option>
<option value="<?php echo $term_two_date ?>">Spring Term ends on <?php echo $term_two_date ?></option>
<option value="<?php echo $term_three_date ?>">Summer Term ends on <?php echo $term_three_date ?></option>
</select>
$enrolled_term = explode(" ", $_POST['enrolled_term']) ;
Try this : to get last selected value (from array)
$total_selected = count($_POST['enrolled_term']);
$enrolled_term = $_POST['enrolled_term'][$total_selected-1] ; //last index
To get the last element of an array, use array_slice()
:
$lastElement = array_values(array_slice($_POST['enrolled_term'], -1))[0];
array_slice — Extract a slice of the array
Just get last item in $_POST['enrolled_term'] . Use end() in PHP end($_POST['enrolled_term'])
or $_POST['enrolled_term'][count($_POST['enrolled_term']) - 1]
Use count() function to get the last items which equals count-1
$terms = explode(" ", $_POST['enrolled_term']) ;
$enrolled_term =$terms[count($terms)-1];
You can try this simplest one, Here we are using end
function.
$enrolled_term=end($_POST['enrolled_term']);