-2

Possible Duplicate:
PHP get both array value and array key

I am using Codeigniters' form_checkbox() method.

Using a foreach loop I am creating the form_checkbox and the forms' label. This is all fine, But I need to get the value from the array.

My array setup is as follows :

Array
(
    [1] => Animals
    [2] => Art and Culture
    [3] => Children
    [4] => Disability
    [5] => Disaster Relief
    [6] => Domestic Violence
);

My PHP code is as follows :

<?php foreach($interests as $interest)
        {
            echo form_checkbox('user_interests[]', $interest);
            echo "<label>$interest</label>";
        }
?>

This produces HTML Like :

<input type="checkbox" value="Animals" name="user_interests[]">

What I would like it to be is the value = "1", "2" etc from the Array key.

How do I get this?

0

5 Answers 5

5

Change your loop to be:

foreach($interests as $key => $interest) {
  ...
}
Sign up to request clarification or add additional context in comments.

Comments

2

change your php code to this:

foreach($interests as $key => $interest)
{
    echo form_checkbox('user_interests[]', $key);
    echo "<label>$interest</label>";
}

Comments

2

Use this code:

foreach($interests as $key => $interest)

Comments

1

try this :

<?php foreach($interests as $k=> $interest)
        {
           $data= array('name'=>'user_interests[]', 'value'= $k)
            echo form_checkbox($data);
            echo "<label>$interest</label>";
        }
?>

Comments

1

Like this:

foreach ($interests as $key => $interest) {
  echo form_checkbox("user_interests[$key]", $interest);
  echo "<label>$interest</label>";
}

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.