0

$a = ['Ava', 'Emma', 'Olivia']; $b = ['Olivia', 'Sophia', 'Emma'];

I want the output to be ['Emma', 'Olivia', 'Ava', 'Sophia'] in any particular order without using array functions.

This is what i tried

<?php
//function unique_names($a,$b){
$a = ['Ava', 'Emma', 'Olivia'];
$b = ['Olivia', 'Sophia', 'Emma'];
$z= $a;
$c = count($b);
$d = count($a);
//loop for b
    $e = 0;
for($i=0;$i<$c;$i++){ //b
    
    for($j=0;$j<$d;$j++){
            
        if($b[$i] != $a[$j]){
        $z[$d+1] = $b[$i];
        break;
        }else{
            //$z[$e] = $a[$j];
        }
  
    }
    
 
        
    
}
echo"<pre>ans";print_r($z);
die;
//return $z;
//}


//echo"<pre>ans"; print_r(unique_names($a,$b));
?>

Also i made it work using in_array but was later told that even that function is not allowed.

<?php
function unique_names($a,$b){
$z= $a;
$c = count($b);
$d = count($a);
for($i=0;$i<$c;$i++){
    
  if(! in_array($b[$i], $a)){
            $z[$d+1] = $b[$i];
  }
        
    
}
return $z;
}
$a = ['Ava', 'Emma', 'Olivia'];
$b = ['Olivia', 'Sophia', 'Emma'];

print_r(unique_names($a,$b));
?>
12
  • Does this answer your question? PHP merge arrays with only NOT DUPLICATED values Commented May 13, 2021 at 15:26
  • 2
    "...without using array functions" sounds like an assignment. So, what have you tried? Where did you get stuck? Please note that while we're glad to help with any issues you encounter, you are still expected to make an honest effort at solving this task yourself. Commented May 13, 2021 at 15:28
  • I have made the changes in question and have added what i tried. Thanks Commented May 13, 2021 at 15:47
  • what about array_unique(array_merge($a, $b)); Commented May 13, 2021 at 15:58
  • 1
    @nice_dev The output needs to be ['a' ,'b' , 'c'] Commented May 13, 2021 at 17:11

1 Answer 1

2

You can use next code:

<?php
$a = ['Ava', 'Emma', 'Olivia']; 
$b = ['Olivia', 'Sophia', 'Emma'];

$values = [];

// Add values from first array
foreach($a as $v) {
    $values[$v] = true;
}

// Add values from second array
// all exists names will be overwrited
// new values will be addded
foreach($b as $v) {
    $values[$v] = true;
}

// Transform keys to plain result
foreach($values as $key=>$val) {
    $result[] = $key;
}
var_dump($result);

Execute PHP online

Sign up to request clarification or add additional context in comments.

Comments

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.