-2

I have two arrays I want to search from first array by key only which i have in second array and as third array i want to print result:

$colldata=array("bench-press-rod"=>'',"adidas-classic-backpack"=>'93549559913',"adidas-classic-backpack-legend-ink-multicolour"=>'',"puma-suede-classic-regal"=>'93549920361,93549723753');
$colldata2=array(0 => 'bench-press-rod',1 => 'adidas-classic-backpack');

Expected result:

array('bench-press-rod'=>'',"adidas-classic-backpack"=>'93549559913');
1

3 Answers 3

1

You can do this in one line in PHP, using array_flip to swap the keys and values of the second array, and then array_intersect_key to merge the two arrays on matching keys:

$colldata=array("bench-press-rod"=>'',"adidas-classic-backpack"=>'93549559913',"adidas-classic-backpack-legend-ink-multicolour"=>'',"puma-suede-classic-regal"=>'93549920361,93549723753');
$colldata2=array(0 => 'bench-press-rod',1 => 'adidas-classic-backpack');

print_r(array_intersect_key($colldata, array_flip($colldata2)));

Output:

Array
(
    [bench-press-rod] => 
    [adidas-classic-backpack] => 93549559913
)

Demo on 3v4l.org

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

Comments

1

About the simplest I can come up with is to loop through the second array and add the matching key from the first array into the output. If the item isn't present then it puts Not found in the output...

$output = [];
foreach ( $colldata2 as $item ) {
    $output[$item] = $colldata[$item] ?? 'Not found';
}
print_r($output);

gives..

Array
(
    [bench-press-rod] => 
    [adidas-classic-backpack] => 93549559913
)

Comments

0

Check this.

$colldata=array("bench-press-rod"=>'',"adidas-classic-backpack"=>'93549559913',"adidas-classic-backpack-legend-ink-multicolour"=>'',"puma-suede-classic-regal"=>'93549920361,93549723753');
$colldata2=array(0 => 'bench-press-rod',1 => 'adidas-classic-backpack');

$result = [];
foreach ($colldata2 as $key => $value) {
    if (array_key_exists($value, $colldata)) {
        array_push($result,$colldata[$value]);
    }            
}
echo '<pre/>';
print_r($result);

Comments

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.