Home > Software design >  How to check not in an array PHP
How to check not in an array PHP

Time:12-08

I am trying to check if an element is not in array and if is not I will add new element.

My array like this

$array = [
       {"date":"05 22","test1":"5","test2":"5"},
       {"date":"06 22","test1":"6","test2":"6"},
       {"date":"07 22","test1":"7","test2":"7"},
       {"date":"08 22","test1":"8","test2":"8"},
       {"date":"09 22","test1":"9","test2":"9"},
       {"date":"10 22","test1":"10","test2":"10"},
       {"date":"11 22","test1":"11","test2":"11"}
      ];


if(!in_array(date("m y"),$array['date']){
    $array[] = ['date' => date("m y"), 'test1' => '12', 'test2' => '12'];
}

The element I will search for is by date (present month of year like date("m y") = 12 22 ) I am confused how to check if element is not in array. I am using (!in_array) but not get the correct logic.

CodePudding user response:

I assume that according to your tags, you are trying to make it with PHP. One of the possible ways is to use the array_column function, for example:

$array = [
   ["date" => "05 22","test1" => "5","test2" => "5"],
   ["date" => "06 22","test1" => "6","test2" => "6"],
   ["date" => "07 22","test1" => "7","test2" => "7"],
   ["date" => "08 22","test1" => "8","test2" => "8"],
   ["date" => "09 22","test1" => "9","test2" => "9"],
   ["date" => "10 22","test1" => "10","test2" => "10"],
   ["date" => "11 22","test1" => "11","test2" => "11"]
  ];
  
  if (!in_array(date("m y"), array_column($array, "date"))) {
        $array[] = [
           'date' => date("m y"), 
           'test1' => '12', 
           'test2' => '12'
        ];
  }

CodePudding user response:

You can use array_column() to get an array of all the 'date' values and then use in_array() to check if the date exists.

$dates = array_column($array, 'date');
if (!in_array(date('m y'), $dates)) {
    $array[] = ['date' => date('m y'), 'test1' => '12', 'test2' => '12'];
}

CodePudding user response:

First off, your array of items needs to be updated to work as a PHP multidimensional array. An array of JSON objects doesn't work in PHP.

<?php

$array = [
    ["date" => "05 22","test1" => "5","test2" => "5"],
    ["date" => "06 22","test1" => "6","test2" => "6"],
    ["date" => "07 22","test1" => "7","test2" => "7"],
    ["date" => "08 22","test1" => "8","test2" => "8"],
    ["date" => "09 22","test1" => "9","test2" => "9"],
    ["date" => "10 22","test1" => "10","test2" => "10"],
    ["date" => "11 22","test1" => "11","test2" => "11"],
];

$searchDate = date('m y');

// Filter the array down by your search criteria
$results = array_filter($array, function($v) use ($searchDate) {
    return $v['date'] === $searchDate;
});

// If it doesn't find any results then you can add a row
if (count($results) === 0) {
    // searchDate not found, add a row
}
  • Related