I am getting the values from database as an array
<?php
foreach($this->getlist as $value){
foreach($this->listOfdealers as $list){
?>
<tr>
<td>
<input type="checkbox" name="list[]" value=<?php echo $list->nList?>
<?php if($value->nSubList==$list->nList){echo 'checked'; } ?> />
<label for="list_32"><?php echo $list->nList?>
</label>
</td>
</tr>
<?php
}
}
?>
I just want to compare two array values and display the checkbox checked when they are equal, but here there are displaying 16 checkbox instead of four,as I am using two for loops and I dont want that.
$this->getlist is an array that is returning from database
use
foreach (array_expression as $key => $value)
statement
from foreach-manual page
so you can use the same index for getting the values
<?php
foreach($this->getlist as $index => $value)
{
$list = $this->listOfdealers[$index];
?><tr>
<td>
<input type="checkbox" name="list[]" value=<?php
echo $list->nList ?>
<?php if($value->nSubList==$list->nList){echo 'checked'; } ?> />
<label for="list_32"><?php echo $list->nList?>
</label>
</td>
</tr>
<?php
}
?>
You can use in_array function in php to compare array values. You can check on http://php.net/manual/en/function.in-array.php for further details. Hope this helps.
Please find the solution below for your problem. It is the sample code using the in_array and array_diff. You can use either of the functionality.
<?php
$var1 = array("test","test1","test2");
$var2 = array("test","test1","test2","test3");
$var3 = array();
foreach($var1 as $i)
{
if(in_array($i,$var2))
{
//save the value
array_push($var3,$i);
}
else
{
continue;
}
}
//var3 will contain the values that are common in two arrays
//Another Method using array_diff
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
print_r($result);
?>
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.