1

I have two arrays:

$mainArray = array(
        ['id' => 1, 'name' => 'test'],
        ['id' => 2, 'name' => 'news'],
        ['id' => 3, 'name' => 'foo'],
        ['id' => 4, 'name' => 'bar']...
        );

$array = array(1,2,5,6,7);

I need to check if the id from the $mainArray is contained in the $array, and if it is contained it needs to print the name. How can I do this?

2 Answers 2

3

simple!

foreach($mainArray as $arr) {
    if(in_array($arr['id'], $array)) {
        echo $arr['id'];
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

This should work for you:

(With this solution you have an array with the id as key and the name as value)

<?php

    $mainArray = array(
                    ['id' => 1, 'name' => 'test'],
                    ['id' => 2, 'name' => 'news'],
                    ['id' => 3, 'name' => 'foo'],
                    ['id' => 4, 'name' => 'bar']
                );

    $array = array(1,2,5,6,7);
    $result = array();

    foreach($mainArray as $k => $v)
        $result[$v["id"]] = (array_intersect($mainArray[$k], $array) ? $mainArray[$k]["name"] : "");

    $result = array_filter($result);
    print_r($result);

?>

Output:

Array ( [1] => test [2] => news )

And you can easy go through the array an print every thing like this:

array_walk($result, function($value, $key) { 
    echo "Key: $key Value: $value <br />";
});

//OR

foreach($result as $key => $value)
    echo "Key: $key Value: $value <br />";

Output:

Key: 1 Value: test 
Key: 2 Value: news 

3 Comments

While this does work, it does seem a little convoluted and prone to false positives. First, you are adding every id to the $result array and then removing them later, why not just check and add only the ones that match? And second using array_intersect will check all vals in the sub array. If there was another column that had a value that matched one of the ids found in $array, for example if a count was added that had a count of times the name existed in another table, it would create a false positive. Also, using array_intersect will check all values when only 1 needs to be checked.
@JonathanKuhn I think you can write this in like 5 different ways at least and all would work! So i don't wanted to post the same solution as Zach Spencer did, i wanted to show another way! And you're compeletly right, but it's every time a question what OP needs.
I understand, but while it is a valid way, it technically isn't the correct way because this will only cause more problems later on when making changes to the code.

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.