Nagesh Katke
Nagesh Katke

Reputation: 578

match values of arrays with different values and different order php

I have two arrays

$array1 = array(
    'categories',
    'questions',
    'difficulties'
);

and

$array2 = array(
     [0] => 'categories_view',
    [1] => 'categories_delete',
    [2] => 'questions_view',
    [3] => 'questions_edit',
    [4] => 'difficulties_view',
)

I want to match values of above arrays for checkbox checked attribute

I tried below code but didn't get proper output.

<?php 
foreach ($array1 as $key => $value) { 
?>
 <div class="col-sm-offset-2 col-sm-3">
  <b><?php echo ucwords($value); ?></b>
 </div>
 <div class="col-sm-2">
  <input type="checkbox" name="role[]" value="<?php echo $value;?>_view" <?php echo $array2[$key] ==  $value."_view". ? $checked : ''; ?> > View
 </div>
 <div class="col-sm-2">
  <input type="checkbox" name="role[]" value="<?php echo $value;?>_edit" <?php echo $array2[$key] ==  $value."_edit". ? $checked : '' ; ?> > Edit
 </div>
 <div class="col-sm-2">
  <input type="checkbox" name="role[]" value="<?php echo $value;?>_delete" <?php echo $array2[$key] ==  $value."_delete". ? $checked : ''; ?> > Delete
 </div>
<?php
}
?>

Output should be enter image description here

Thanks in advance

Upvotes: 1

Views: 26

Answers (2)

Arthur  Qocharyan
Arthur Qocharyan

Reputation: 958

<?php foreach ($array1 as $key => $value) :?>
 <div class="col-sm-offset-2 col-sm-3">
  <b><?php echo ucwords($value); ?></b>
 </div>
 <div class="col-sm-2">
  <input type="checkbox" name="role[]" value="<?php echo $value;?>_view" <?php echo in_array($value . "_view", $array2) ? $checked : ''; ?> > View
 </div>
 <div class="col-sm-2">
  <input type="checkbox" name="role[]" value="<?php echo $value;?>_edit" <?php echo in_array($value . "_edit", , $array2) ? $checked : '' ; ?> > Edit
 </div>
 <div class="col-sm-2">
  <input type="checkbox" name="role[]" value="<?php echo $value;?>_delete" <?php echo in_array($value . "_delete", $array2) ? $checked : ''; ?> > Delete
 </div>
<?php endforeach; ?>

Upvotes: 0

u_mulder
u_mulder

Reputation: 54831

It is simple, just check if required value presents in $array2 with in_array function:

<?php
foreach ($array1 as $key => $value) {
?>
 <div class="col-sm-offset-2 col-sm-3">
  <b><?php echo ucwords($value); ?></b>
 </div>
 <div class="col-sm-2">
  <input type="checkbox" name="role[]" value="<?php echo $value;?>_view" <?php echo in_array($value . "_view", $array2) ? $checked : ''; ?> > View
 </div>
 <div class="col-sm-2">
  <input type="checkbox" name="role[]" value="<?php echo $value;?>_edit" <?php echo in_array($value . "_edit", , $array2) ? $checked : '' ; ?> > Edit
 </div>
 <div class="col-sm-2">
  <input type="checkbox" name="role[]" value="<?php echo $value;?>_delete" <?php echo in_array($value . "_delete", $array2) ? $checked : ''; ?> > Delete
 </div>
<?php
}
?>

Upvotes: 1

Related Questions