Page 1 of 1

Of: in_array, foreach and multi-dimensional arrays

Posted: Mon Sep 02, 2002 9:36 pm
by phpPete
Ealier today Iwas stymied by in_array with multidimensional array.

Essentially I have 2 arrays, both returned from mysql via a function which executes the query(s) and returns an array.

$array_1 structure looks something like this:

Code: Select all

array
(
    ї0]=>Array
                (
                     ї0]=> some_item
                )
    ї1]=> Array
              (
                ї0]=> some_item
               )

on through 100
$array_2 has a similar structure, but, it's only about 7 elements in length.

I was attempting to use a foreach to iterate over the shorter array and use in_array to check for a value, however, the difference in array lengths got me stuck. The bottom line is how would one use in_array on multidimensional array?

Code: Select all

My attempts were along these lines

foreach( $array_2 as $temp ) 
{
    if( in_array( $tempї0], $array_1 ))// or array_1ї0]  ??
               {
                   do something...
               }
}


For my purposes I ended-up flattening both arrays to one dimension, but I'd to know how to make my original array do the job

Posted: Mon Sep 02, 2002 9:53 pm
by volka
you really can compare arrays in php.

Code: Select all

<?php $pattern= array( 'this', 'is', 'just', 'a', 'test');

if($pattern == array( 'this', 'is', 'just', 'a', 'test')) // <- this is true
	print('true');

if($pattern == array( 'this', 'is', 'just', 'a', 'fake')) // <- this isn't
	print('true');
?>
And so you can use in_array to find wether an array is included in another array or not.

Code: Select all

<?php $pattern= array( 'this', 'is', 'just', 'a', 'test');
$arr1 = array( $pattern, array('somthing', 'else') );
print( (in_array($pattern, $arr1)) ? 'true' : 'false');
?>
will print "true"

also will

Code: Select all

<?php $pattern= array( 'this', 'is', 'just', 'a', 'test');
$arr1 = array( $pattern, array('somthing', 'else') );
print( (in_array(array( 'this', 'is', 'just', 'a', 'test'), $arr1)) ? 'true' : 'false');
?>
print "true"

The arrays must not only contain the same values in the correct order but have to be identical(*)

Code: Select all

<?php $pattern= array( 'this', 'is', 'just', 'a', 'test');
$arr1 = array( $pattern, array('somthing', 'else') );

$search = array( 'this', 'is', 'foobar', 'just', 'a', 'test');
unset($searchї2]);

print( (in_array(array( 'this', 'is', 'just', 'a', 'test'), $arr1)) ? 'true' : 'false');?>
this will print "false"


(*) each key/value-pair must match:
array( 'this', 'is', 'just', 'a', 'test') equals array( 2=>'just', 0=>'this', 1=>'is', 3=>'a', 4=>'test')