By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy

Q: Common Elements - PHP Array Task

+4 votes

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.


common elements php array task

asked in PHP category by user andrew

1 Answer

+3 votes



$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().

answered by user eiorgert