Jump to content

PHP in_array Displays only one result


Leatfield

Recommended Posts

Hi There, I have the following code:

two arrays:

$user_body_group & $DB_Seconday_muscles

 

I want to look up the "$DB_Seconday_muscles" Array and search for the elements in the "$user_body_group" array

 

The result would be displaying a checkbox list with only the items in the "$user_body_group" array checked:

 

 

foreach($DB_Seconday_muscles as $value) {

 

 

echo "<input name=\"colors[]\" type=\"checkbox\" value=\"$value\"";

 

if (in_array($value,$user_body_group))

{

echo "CHECKED";

}

 

 

echo "> $value ";

 

}

 

BUT... When i run thi script i only get the first element in the searched array ticked.

 

Can anyone help!

 

Many Thanks!

 

Leatfield

Link to comment
Share on other sites

Well, the values will need to be EXACTLY the same for in_array() to return true. Other than that the logic looks correct. However, the HTML is not formatted correctly. For one, there is no space after the closing quote of the value and to correctly check a field you should use checked="checked". BUt, that doesn't seem to be the cuase of the issue you are describing.

 

This code is a little more efficient. If you still have problems with this code post the contents of the arrays for further help

foreach($DB_Seconday_muscles as $value)
{
    $checked = (in_array($value, $user_body_group)) ? ' checked="checked"' : '';
    echo "<input name=\"colors[]\" type=\"checkbox\" value=\"{$value}\"{$checked}> {$value} \n";
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.