Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php looping through multiple arrays [duplicate]

Tags:

arrays

loops

php

okay so I have two arrays

$array_one([a]=>2,[b]=>1,[c]=>1);
$array_two([a]=>1,[b]=>2,[c]=>1);

I want to be able to loop through both of these arrays simultaneously so I can make simple comparisons. I looked at using a foreach loop but I can only process the information one array at a time. I also looked at merging the arrays but I can not see the use in doing this since I need both the keys and values to make the comparisons. does anyone have a solution to this problem? I appreciate your time in advanced.

to be specific on the comparisons i want to something to this extent

if ($keyone == $keytwo && $valuetwo <= $valueone)
{
   print_r ($array_two);
}

Would it be possible to use recursion to loop instead of using and iterative loop?

like image 555
jkdba Avatar asked Feb 07 '12 05:02

jkdba


2 Answers

$array_one = array (
    'a' => 2,
    'b' => 1,
    'c' => 1
);
$array_two = array (
    'a' => 1,
    'b' => 2,
    'c' => 1
);


$iterator = new MultipleIterator ();
$iterator->attachIterator (new ArrayIterator ($array_one));
$iterator->attachIterator (new ArrayIterator ($array_two));

foreach ($iterator as $item)
{
    if ($item [0] > $item [1])
    {
        ...
    }
}

It's a little bit superfluous, really, but I see a certain beauty in it.

like image 71
akond Avatar answered Oct 13 '22 23:10

akond


If they have the same keys you can just loop through the keys and use them to index the arrays using array_keys:

foreach(array_keys($array_one) as $key) {
    // do something with $array_one[$key] and $array_two[$key]
}

If you're worried about some keys not existing you can try (e.g.) array_key_exists($key,$array_two).

like image 31
mathematical.coffee Avatar answered Oct 14 '22 00:10

mathematical.coffee