简体   繁体   中英

Array to String Conversion error in Codeigniter

Well I am Stuck some where here in Array conversion:

My Controller:

$username = $this->input->post('FirstName');
$countryval= $this->input->post('country');

var_dump($countryval);

My View:

<input type="text" name="FirstName" id="Name" >
<?php
foreach ($countryDetails as $row )
{
    echo '<input id="country" type="checkbox" name="country[]" class="unique"  value="'.$row->country_id.'">'.$row->country_name.'<br/>';
}
?>
<script>
    $('input.unique').click(function() {
        $('input.unique:checked').not(this).removeAttr('checked');
    });
</script>

I am getting the value from checkbox in an array and I need to pass that value as a string further. I am not able to convert value from array to string ie if I var_dump($countryval) I get value in array ! Please Help. Thank you

That is because you have used "country[]" as the name in input field

Please try this incase you need a single value to be returned (Edit made here coz I put type="checkbox" instead of "radio".. I have corrected it) Trust radios for single values.

echo '<input id="country" type="radio" name="country" class="unique"  value="'.$row->country_id.'">'.$row->country_name.'<br/>';

hope that helps

You need "country[ ]" as name only if it has multiple values. Eg., For a multiple select

<select name="country[]" multiple>
  <option></option> <!-- Your options go here-->
</select>

You can use input-checkbox too.. But with your question, I believe you need just a single value to be returned.

Ok.. Now From Your comments I kind of get what you want. Here is my suggestion

1) When you are having multiple checkboxes with the same name, the values are sent as an array.

2) If you would need a single value at a time and definitely need a checkbox, You can make a radio look like a checkbox like this.

3) If you really want to proceed with your javascript allowing only one checkbox at a time, you can do this.

// Load the 'array' helper
$this->load->helper('array');
// Use the 'element' function to return an element from the array
$countryval = element('0', $this->input->post('country')); //should work

Have a try..!!

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