0

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);

2 Answers 2

1

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
)
Sign up to request clarification or add additional context in comments.

Comments

0

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);

3 Comments

This won't work if you have a subject called Biochemistry and chemistry. Example.
I just encountered that exact problem with "English" and "English Lit" any ideas?
I encourage you to take a look at my answer. It will work even if the subject contains parts of other subjects.

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.