Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

php combine 2 single dimensional arrays based on shared values

How to merge these two arrays:

$arr1 = array ( 1, 3, 2 );
$arr2 = array ( 1, 2, 4 );

So the result is an array with only the values found in both:

$result = array ( 1, 2 );

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use the array_intersect() function that "returns an array containing all the values of array that are present in all the arguments. Note that keys are preserved."

<?php

$arr1 =  [ 1, 3, 2 ];
$arr2 = [ 1, 2, 4 ];

$result = array_intersect($arr1, $arr2);

?>

Output:

Array ( [0] => 1 [2] => 2 )

You can use the array_values() to "return all the values from the array and index the array numerically."

$result = array_values(array_intersect($arr1, $arr2));

Output:

Array ( [0] => 1 [1] => 2 )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading