PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, May 17, 2022

[FIXED] How to remove values from two arrays that have the same key and value?

 May 17, 2022     arrays, php     No comments   

Issue

I have two arrays:

$array1 = array('[param1]' ,'demo' ,'[param2]' ,'some' ,'[param3]');
$array2 = array('value1'   ,'demo' ,'value2'   ,'some' ,'value3');

I want to compare these two arrays and remove all duplicate values.
In the end, I want these two arrays but without 'demo' and 'some' values in them.
I want to remove all values from arrays that have the same index key and value.
Arrays will always have the same number of values and indexes, I only want to compare them and remove entries that have the same index key and value, from both of them.

I'm doing something like this now:

$clean1 = array();
$clean2 = array();    

foreach($array1 as $key => $value)
{
    if($value !== $array2[$key])
    {
        $clean1[$key] = $value;
        $clean2[$key] = $array2[$key];
    }
}
    
var_export($clean1);
echo "<br />";
var_export($clean2);

And this works! But I'm wondering is there any other way of doing this? Maybe without using foreach loop?


Solution

array_unique( array_merge($arr_1, $arr_2) );

or you can do:

$arr_1_final = array_diff($arr_1, $arr_2);
$arr_2_final = array_diff($arr_2, $arr_1);


Answered By - Mr. BeatMasta
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,217,831

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing