[Solved] Common Elements - PHP Array Task

  

3
Topic starter

Write a program, which prints common elements in two arrays. You have to compare the elements of the second array to the elements of the first.

Examples:

common elements php array task

1 Answer
2

Solution:

<?php
 
$arrayOne = explode(' ', readline());
$arrayTwo = explode(' ', readline());
$arrayCommon = [];
 
$countOne = count($arrayOne);
$countTwo = count($arrayTwo);
 
for ($i = 0; $i < $countOne; $i++) {
    for ($j = 0; $j < $countTwo; $j++) {
        if ($arrayOne[$i] == $arrayTwo[$j]) {
            $arrayCommon[] = $arrayTwo[$j];
        }
    }
}
 
echo implode(' ', $arrayCommon);

I've used explode() and implode() php functions: first to get the strings/integers and create an array with explode() and then to show the elements in the newly created array with implode().

Share: