user1721230
user1721230

Reputation: 315

Compare one array with another and replace missing values php

I have two Arrays:

$a1=array("Maths","English","Science","ICT");
$a2=array("Maths","ICT");

I want to compare $a1 with $a2, then return

$a3=array("Maths",",,",",,","ICT");

So replace the missing values in $a2 with ",,"

This is my meager attempt :(

$a1=array("Maths","English","Science","ICT");
$a2=array("Maths","ICT");
$result = array_diff($a1, $a2);
foreach ($result as $v){
$a3 = str_replace($v, ",,", $a1);
}
print_r($a3);

Upvotes: 0

Views: 397

Answers (2)

Dave Chen
Dave Chen

Reputation: 10975

Glad you figured it out, but I think this might work better:

<?php

$a1 = array("Maths", "English", "Science", "ICT");
$a2 = array("Maths", "ICT");

$a3 = $a1;

$keys = array_keys(array_diff($a1, $a2));
foreach ($keys as $key)
    $a3[$key] = ',,';

print_r($a3);

Output:

Array
(
    [0] => Maths
    [1] => ,,
    [2] => ,,
    [3] => ICT
)

Upvotes: 1

user1721230
user1721230

Reputation: 315

Figured it out, thanks if you looked:

$a1=array("Maths","English","Science","ICT");
$a2=array("Maths","ICT");

$result = array_diff($a1, $a2);

foreach ($result as $v){

$v = str_replace($result, ",,", $a1);

}
print_r($v);

Upvotes: 0

Related Questions