0

I have an string in database : 3,8,10,15

and in script i have an array : $a=array(0=>'music',1=>'computers'....etc), the keys are matching the strings in database.

Then i explode() the string from database with: $a=explode(",",$dbresult) This makes an array like this:

$a =
Array
(
    [0] => 3
    [1] => 8
    [2] => 10
    [3] => 15
)

In script:

<?PHP
$b=array(0=>'music',1=>'Computers','...etc');
    $a = explode(",",$a);
    foreach ( $b as $key => $value ){

    $select = $a==$key ? " checked='checked'" : null;

    echo "<label><input type='checkbox' name='name' value='{$key}'$select/> {$value};
    }}
?>

This ofcourse will not work since its matching the $b arrays keys, and not the values of $a

So my question is.. How can i make it match the $b keys against $a values ?

3
  • I'm not understanding the relationship to $a and $b. Are the keys supposed to align between them such that $a[0] (3) is related to $b[0] (music)? Commented Feb 19, 2012 at 1:18
  • Or do the values of $a relate to the keys of $b such that $a[0] (3) relates to $b[3] ('someotherthing')? Commented Feb 19, 2012 at 1:19
  • Yes, the $a is the keys of $b. Commented Feb 19, 2012 at 1:28

1 Answer 1

1

You're looking for in_array:

<?php
$b = array(0=>'music',1=>'Computers','...etc');
$a = explode(",", '0,3');
foreach ($b as $key => $value) {
    $select = in_array($key, $a) ? " checked='checked'" : null;

    echo '<input type="checkbox" name="name" value="' . $key . '"' . $select . '/>';
    echo $value;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.