2

I have an array with a key and 3 values (day, start_time, end_time). I want to keep adding certain entries into this array while making sure each entry is unique. That means that every time I try to add an item into the array, I want to make sure it does not already exist in it. If it does exist, I want to be able to find the key that indicates that entry.

For example, this is the pre-existing array:

$array [0][0] = Monday
$array [0][1] = 2
$array [0][2] = 4
$array [1][0] = Tuesday
$array [1][1] = 3
$array [1][2] = 5

If I try to insert (Wednesday, 3, 5), then it should make the entry in the index 2.

If I try to insert (Monday, 2, 4), I need to be able to know that it is already in there and is indexed by 0.

How do I go about doing this?

Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989
adrianmc
  • 1,738
  • 1
  • 15
  • 41
  • How about making the day the key. So $array["Monday"][0] = 2 and $array["Monday"][1] = 4. Otherwise you can search the array. Also, what are the default values in the array? Would it just be null or not exist? So before adding (Monday, 2, 4) let's say, would $array[0] exist? Also check this out, http://stackoverflow.com/questions/4128323/php-in-array-and-multidimensional-array may be what you are looking for. – Matt Jul 11 '11 at 22:53

2 Answers2

1

I agree with the other answers here — it might be better to restructure your array so that there is no need to worry about duplication at all.

If you want to keep your current structure, however: use array_search.

$array = ...
$unique_check = array_search(array('Monday', 2, 4), $array);

if ( $unique_check === false )
    // add to array
else
    // $unique_check = the array key at which the existing matching element is located
Jon Gauthier
  • 23,502
  • 5
  • 60
  • 68
0

Why not organize the array this way?

$array [Monday][0] = 2
$array [Monday][1] = 4
$array [Tuesday][0] = 3
$array [Tuesday][1] = 5
SteAp
  • 10,824
  • 8
  • 48
  • 83