Forum Moderators: coopster

Message Too Old, No Replies

Does in_array work on a multidimensional array?

Doesn't seem to.

         

HughMungus

7:32 pm on Jun 5, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I have a multidimensional array that looks something like this:

Array ( [0] => Array ( [id] => 9545 [store] => Some Store Name )[1] => Array ( [id] => 9544 [store] => Some Store Name )

Does in_array work in a multidimensional array (such as if you're adding a new array to a mulidimensional array and only want to add an element if it doesn't already exist in one of the arrays in the multidimensional array)?

coopster

8:17 pm on Jun 5, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Sure, as of PHP 4.2.0, your search parameter is allowed to be an array.
$id = 9545; 
$store = 'Some Store Name';
if (in_array(array('id' => $id, 'store' => $store), $array)) {
print "Found!";
}

HughMungus

8:29 pm on Jun 5, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks coopster. Hadn't thought of using the whole array to do the comparison. The problem now, though, is that I have a unique id for each listing in the database that would make it so that I can't do an array comparison (because the unique id of each row in the table makes each array unique even if all the other data on that row is the same as some other row).

coopster

8:40 pm on Jun 5, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Then why not change your array structure so that the id is your array key when building your array of values?
$a = array( 
9545 => array('store' => 'Some Store Name'),
9544 => array('store' => 'Some Store Name')
);
$id = 9545;
$store = 'Some Store Name';
if (in_array($store, $a[$id])) print "Found!";

HughMungus

10:06 pm on Jun 5, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Ah yes, that might work. Thanks!