Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching multiple values against an array

My problem is:

I have an array called $ownerArray that another array need to check against and if a key exists in both arrays display the value of the matching key. $ownerArray is populated by a database so i can't just write an ir statement within a if statement.

$ownerArray will look like this:

$ownerArray = array(0 =>'Name0',1 =>'Name1',2 =>'Name2',3 =>'Name3');

Then I have another array called $Users that has a various number of values depending on what the user selects, so $Users could look like this:

$Users = '1,2'

or Like this:

$Users = '1,3'

$Users is never the same.

But I need the $value of $ownerArray to display if any of the values integers of $Users match any $key of $ownerArray

Example:

foreach($ownerArray as $key => $value) 
            { 
                if(in_array($key,array($Users)))
                {
                    print $value; 
                } 
            }

This method stops at the fist match and displays the correct name. The loop doesn't continue printing if more values match.

What im looking for is if $Users = '1,3' my for loop will print Name1 and Name3 from the $ownerArray.

Thanks for the help!

ps i know i could use if($key==1 || $key ==2) but that will not work for this case.

like image 410
knittledan Avatar asked Aug 26 '26 00:08

knittledan


2 Answers

$merged = array_flip(array_intersect(array_flip($owners), explode(',', $users)));

something like this could work

<?php

$ownerArray = array(0 =>'Name0',1 =>'Name1',2 =>'Name2',3 =>'Name3');
$users = explode(',','1,2');

if(count($users) > 0){
    foreach($users as $user){
        if($key = array_search($user,$ownerArray)){
            echo $key;
        }
    }
}


?>
like image 29
Mikey Avatar answered Aug 27 '26 14:08

Mikey