0

Let's say I need to run a for loop through an array where I need to check against to key value. I would like to print the array element that doesn't match BEFORE the element that doesn't match.

So using the array from below (extra values added for clarity), I would like it to print as follows. It needs to match the current_tag and last_tag values. If they don't match, that key needs to be printed prior to the others.

Desired results

TEST2

TEST1 
TEST3 
TEST4 

Array

array(2) {
    [0]=>
    array(3) {
        ["name"]=>
            string(3) "TEST1"
        ["current_tag"]=>
            string(13) "20121129_TEST1"
        ["last_tag"]=>
            string(13) "20121129_TEST1"
    }
    [1]=>
    array(3) {
        ["name"]=>
            string(3) "TEST2"
        ["current_tag"]=>
            string(13) "20121205_TEST2"
        ["last_tag"]=>
            string(13) "20121129_TEST2"
    }
    ...
    ...
    ...
    ...
}

1 Answer 1

1

I would usort the array with a custom callback to sort the array. After sorting you can just print every name key.

usort($array, function($a, $b) {
    $match_a = $a['current_tag'] == $a['last_tag'];
    $match_b = $b['current_tag'] == $b['last_tag'];

    if ($match_a && $match_b) {
        return 0;
    } elseif ($match_a && !$match_b) {
        return 1;
    } elseif (!$match_a && $match_b) {
        return -1;
    }
});

array_walk($array, function($item) {
    echo $item['name'];
});

If it is ordered in the wrong order just switch the 1 and -1 return values.

Sign up to request clarification or add additional context in comments.

1 Comment

Just thought of something, while that works and all, I need a way to "separate" them. So, it should print the values that don't match first and maybe followed by a break to differentiate itself from the other array values. See my example above.

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.