Missing one value while using in_array in php

Viewed 213

I have two arrays and below is the output. The first array is my all the list and the second I am getting by the user selected.

$specification=getgeneralSpecifications($pdo); // getting below array

Array(
    [0] => Array
        (
            [sp_id] => 1
            [specifications_name] => example 1
        )

    [1] => Array
        (
            [sp_id] => 2
            [specifications_name] => example 2
        )

    [2] => Array
        (
            [sp_id] => 3
            [specifications_name] => example 3
        )

    [3] => Array
        (
            [sp_id] => 4
            [specifications_name] => example 4
        )

    [4] => Array
        (
            [sp_id] => 5
            [specifications_name] => example 5
        )

    [5] => Array
        (
            [sp_id] => 6
            [specifications_name] => example 6
        )

)
    $getgeneral = explode(",",$info['developerprofile']['general_Specifications']); // getting below output

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

I have to display all the lists from the database and I have checked the check box depending on the second array value getting the form database.

I tried the below code and I am getting the output but missing one value. I mean if I have array 1,2,3,4 then I am getting on 1,2,3

    <?php 
    $specification=getgeneralSpecifications($pdo);
    $getgeneral = explode(",",$info['developerprofile']['general_Specifications']);

    foreach ($specification as $key=> $row) {
      $checked="";
      if(in_array($key, $getgeneral)){
        $checked="checked";
          }
      ?>
      <li><label><?php echo $row['specifications_name'];?></label>
        <div class="form-check">
          <input class="form-check-input custom-checkbox generalsinglecheck" type="checkbox" value="<?php echo $row['sp_id'];?>" name="general_specification[]" <?php echo $checked;?>>
        </div>
      </li>
    <?php } ?>
2 Answers

This is a simple matter of mistaking the row indexes and the sp_id values (which are also numeric).

Your $key variable would be more aptly named $index, but the truth is that you don't need to declare that variable at all. Instead, reference the row's sp_id when comparing against the $getgeneral array and everything will be fine.


I recommend creating a clean template string to use as you iterate. printf() is great for this technique. This way you can neatly tab your markup and you don't need to use messy interpolation/concatenation mixed with inline condition blocks.

Oh, and I'll demonstrate array destructuring within the foreach(), but you don't necessarily need to do this -- you can just access the subarray values by their key if you wish.

Code: (Demo) (Demo without destructuring)

function getgeneralSpecifications() {
    return [
        ['sp_id' => 1, 'specifications_name' => 'example 1'],
        ['sp_id' => 2, 'specifications_name' => 'example 2'],
        ['sp_id' => 3, 'specifications_name' => 'example 3'],
        ['sp_id' => 4, 'specifications_name' => 'example 4'],
        ['sp_id' => 5, 'specifications_name' => 'example 5'],
        ['sp_id' => 6, 'specifications_name' => 'example 6'],
    ];
}

$checked = explode(',', '1,2,4');

echo "<ul>";
foreach (getgeneralSpecifications() as ['sp_id' => $id, 'specifications_name' => $name]) {
    printf(
        '<li>
            <label>%s</label>
            <div class="form-check">
                <input class="form-check-input custom-checkbox generalsinglecheck"
                       type="checkbox"
                       value="%d"
                       name="general_specification[]"
                       %s>
            </div>
        </li>',
        $name,
        $id,
        in_array($id, $checked) ? 'checked' : ''
    );
}
echo "</ul>";

Output:

<ul>
    <li>
        <label>example 1</label>
        <div class="form-check">
            <input class="form-check-input custom-checkbox generalsinglecheck"
                   type="checkbox"
                   value="1"
                   name="general_specification[]"
                   checked>
        </div>
    </li>
    <li>
        <label>example 2</label>
        <div class="form-check">
            <input class="form-check-input custom-checkbox generalsinglecheck"
                   type="checkbox"
                   value="2"
                   name="general_specification[]"
                   checked>
        </div>
    </li>
    <li>
        <label>example 3</label>
        <div class="form-check">
            <input class="form-check-input custom-checkbox generalsinglecheck"
                   type="checkbox"
                   value="3"
                   name="general_specification[]"
                   >
        </div>
    </li>
    <li>
        <label>example 4</label>
        <div class="form-check">
            <input class="form-check-input custom-checkbox generalsinglecheck"
                   type="checkbox"
                   value="4"
                   name="general_specification[]"
                   checked>
        </div>
    </li>
    <li>
        <label>example 5</label>
        <div class="form-check">
            <input class="form-check-input custom-checkbox generalsinglecheck"
                   type="checkbox"
                   value="5"
                   name="general_specification[]"
                   >
        </div>
    </li>
    <li>
        <label>example 6</label>
        <div class="form-check">
            <input class="form-check-input custom-checkbox generalsinglecheck"
                   type="checkbox"
                   value="6"
                   name="general_specification[]"
                   >
        </div>
    </li>
</ul>

i dont understant your code ,But why you not try use your checkbox as an array in java script, By try something like,

Example :

<?php
//you-php-response.php
require "database.php";
$db = new DataBase();
if (isset($_POST['sp_id']) ) {
    if ($db->dbConnect()) {
        if ($db->setlist("my_list_2", $_POST['sp_id'])) {
            echo "Add to list";

        } else echo "something went wrong";
    } else echo "Error: Database connection";
} else echo "All fields are required";

and your database.php :

<?php
require "DataBaseConfig.php";

class DataBase
{
    public $connect;
    private $stm;
    protected $servername;
    protected $username;
    protected $password;
    protected $databasename;

    public function __construct()
    {
        $this->connect = null;
        $this->stm = null;
        $dbc = new DataBaseConfig();
        $this->servername = $dbc->servername;
        $this->username = $dbc->username;
        $this->password = $dbc->password;
        $this->databasename = $dbc->databasename;
    }

    function dbConnect()
    {
        $this->connect = new PDO('mysql:host='.$this->servername.';dbname='.$this->databasename.'', $this->username, $this->password);
        return $this->connect;
    }

    function setlist($table, $sp_id)
    {
         $this->stmq = "INSERT INTO ".$table."( `sp_id_token`) VALUES ('?')";
         $this->stm = $this->connect->prepare($this->stmq) ;
          if ($this->stm->bind_param("ssis", $this->my_sup_id)) {
              $this->my_sup_id = "$sp_id";
              $this->stm->execute();
             return true;
           } else return false;  
    }

    function getmycheckboxRander()
    {
         $this->stmq = "SELECT* FROM `my_list_1` ";
         $this->stm = $this->connect->prepare($this->stmq);
         $this->stm->execute();
         $this->result =   $this->stm->fetchAll();
         $this->body = array();
         foreach($this->result as $this->row){
              $this->sp_id= $this->row['sp_id'];
              $this->my_sup_name = $this->row['sup_name'];
              $this->body[] = array("<div class='card ew-card card-body'><p><input 
             type='checkbox' name='type' value=".$this->sp_id." />".$this->my_sup_name." </p></div>");
        }
     return $this->body;
    }
}

and 'DataBaseConfig.php'

<?php

class DataBaseConfig
{
    public $servername;
    public $username;
    public $password;
    public $databasename;

    public function __construct()
    {

        $this->servername = 'localhost';
        $this->username = 'root';
        $this->password = 'pass@';
        $this->databasename = 'data_base';

    }
}

?>

and your script should be like

<?php
require_once "database.php";
$db = new DataBase();
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
<?php if($db->dbConnect()){?>
    var mylist= <?= json_encode($db->getmycheckboxRander())?>;
<?php }?>
    document.getElementById("mylistarray").innerHTML = mylist;
        $('button').on('click', function() {
            var array = [];
            $("input:checkbox[name=type]:checked").each(function() {
                var sup_id = $(this).val();
                jQuery.ajax({
                   url:'your-php-response.php',
                    type:'post',
                    data:'sp_id ='+sup_id ,
                        success:function(result){
                          window.location.href=window.location.href 
                     }
                 });
            });          
        });
</script>
//then the result
<div id="mylistarray"></div>
  <button class="btn btn-success" >Add to list</button>
Related