3

i have an array with times and ids and i am adding new times to it with different id and i need to check if it exists first. ex.

first array

$times = array(
    array('start'=>"1:00","end"=>"1:59","id"=>1),
    array('start'=>"2:00","end"=>"2:59","id"=>1),
    array('start'=>"3:00","end"=>"3:59","id"=>1),
    array('start'=>"4:00","end"=>"4:59","id"=>1),
    array('start'=>"5:00","end"=>"5:59","id"=>1),
    array('start'=>"6:00","end"=>"6:59","id"=>1)
);

need to do

$time = array('start'=>"2:00","end"=>"2:59","id"=>2);
if(!in_array($time,$times){ // here is the problem 
    array_push($times,$time);
}

this is not duplicated because its not about the pair key/value since its always the same its about having the same pair of key/value but checking if a new element - regardless of its id key value - already exists in the array

0

1 Answer 1

4

Since the id keys are different, you cannot use array comparison functions and operators directly. I would recommend simply iterating the array and comparing the keys:

$found = false;
foreach ($times as $key => $t) {
  if ($t['start'] == $x['start'] && $t['end'] == $x['end']) {
    $found = true;
    $times[$key] = $x;
    break;
  }
}

if (!$found) {
  $times[] = $x;
}

If the number of fields is big, or even is unknown, you can create temporary arrays with the id field unset and compare them with comparison operators:

$tmp_x = $x;
unset($tmp_x['id']);

$found = false;
foreach ($times as $key => $t) {
  $tmp_t = $t;
  unset($tmp_t['id']);

  if ($tmp_t == $tmp_x) {
    $found = true;
    $times[$key] = $x;
    break;
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

This actually fix the problem but then another problem occurs "efficiency" problem since $time here is only an example and what is really happening that i am already doing a nested for to get the $times and then adding new times to it which means extra load on cpu ... but i will accept the solution because it fix it :D
@YamenImadNassif, hmm. If the number of items is big, you need a more efficient search algorithm, such as binary search, or better. Alternatively, you can use a memory-based database (e.g. Redis, or MySQL table with MEMORY engine).
I will go with solution for the moment since i need a fast one and will put more efficient one - if i found - later Thanks.

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.