I have 2 arrays.
<?php
$array1 = array('id' => 1, 'email' => 'example#example.com' , 'name' => 'john' );
$array2 = array('id', 'email');
i am having trouble writing a code to unset the key value pair from array1 that is not from array 2.
The problem with this is unlike most examples, my array2 does not have a format of a key value pair but only key.
How do i go about removing things from array1 that is not specified in array2.
my current code is not working
foreach ($array1 as $key => $value) {
if (array_search($key, $array2)===false) {
unset($key);
}
}
Use array_diff_key() to leave values which are not in second array:
$array1 = array('id'=>1, 'email'=> 'email' , 'name'=>'john' );
$array2 = array('id','email');
$result = array_diff_key($array1, array_flip($array2));
Or, if you want to change first array:
$array1 = array_diff_key($array1, array_flip($array2));
Edit (misunderstanding)
Use array_intersect_key() to leave values which are in second array:
$array1 = array_intersect_key($array1, array_flip($array2));
You are doing it right, just that your way of unset is incorrect:
unset($key);
should be
unset($array1[$key]);
Demo
You have to unset the element by its index (starting from 0)
For example
unset($array2[1]);
will remove the 'email' element.
So in Your case it should be:
unset($array1[$key]);
Related
Lets say I have the following array:
$array_1 = [
'Green' => 'Tea',
'Apple' => 'Juice',
'Black' => 'Coffee',
];
How do I flip the key => value of only one part of the array to something like this:
$array_2 = [
'Tea' => 'Green',
'Apple' => 'Juice',
'Black' => 'Coffee',
];
I know there is a function array_flip() but it flips the whole array, how do I go about flipping only a selected key value pair in the array?
There's nothing that does this. Just assign the flipped key and delete the old key.
$key_to_flip = 'Green';
$array_2 = $array_1;
unset($array_2[$key_to_flip]);
$array_2[$array_1[$key_to_flip]] = $key_to_flip;
The following code just flips all elements of the array. It just does the same thing as array_flip:
$array_2 = array();
foreach ($array_1 as $key => $value) {
$array_2[$value] = $key;
}
Now if you want to flip an element in the array, you need to code like the following. Suppose you want to flip just 'Apple' in your element. You need to wait for that element in a foreach loop, and when you catch it, flip it. Try the following just to flip the 'Apple' key.
$array_2 = array();
foreach ($array_1 as $key => $value) {
if ($key === 'Apple') {
$array_2[$value] = $key;
} else {
$array_2[$key] = $value;
}
}
Try this online!
Say i have two different arrays. I want to get each value from the first array, and add to it some values of each key in the second array. How do i do this please?
I tried using a foreach loop inside a foreach loop and for each value in the first array, it appends each value of the second array which isn't what i want
$array1 = array(chris, kate, john, jane);
$array2 = array('first' => 1, 'second' => 2, 'third' => 3, 'fourth' => 4);
foreach($array1 as $name){
foreach($array2 as $k => $v){
echo $name . "-" . $v;
}
}
I want my output to look like this
chris-1
kate-2
john-3
jane-4
Sometimes, the count of both array aren't the same. Some values in the first array produces an empty string, so in cases like that, it should just skip the value. Once the empty string in array1 is skipped or deleted, the count then matches array2
My above nested loop can't give me this. How do i go about this please?
Firstly I would use array_filter() to remove the empty strings from $array1:
$array1 = array(chris, kate, john, jane);
$array1 = array_filter($array1, function($value) {
return $value !== '';
});
Now we need to reindex the array to account for the gaps we made when removing empty strings.
$array1 = array_values($array1);
Considering you don't use the 'first', 'second', etc keys in $array2 for anything, we can just get rid of them using array_values(). This will leave us with an array like array(1,2,3,4) which will make accessing the data later on a little easier.
$array2 = array('first' => 1, 'second' => 2, 'third' => 3, 'fourth' => 4);
$array2 = array_values($array2);
Now we can loop through the first array and access the same position in the second array to create the final string.
// Assign the current element's numeric position to the $i variable on each iteration.
foreach($array1 as $i => $name){
echo $name . "-" . $array2[$i];
}
Final Code
$array1 = ['chris', 'kate', '', 'john', 'jane'];
$array1 = array_filter($array1, function ($value) {
return $value !== '';
});
$array1 = array_values($array1);
$array2 = ['first' => 1, 'second' => 2, 'third' => 3, 'fourth' => 4];
$array2 = array_values($array2);
foreach ($array1 as $i => $name) {
echo $name . "-" . $array2[$i];
}
I have this array:
$arrayAll = [
'156' => '1',
'157' => '1',
'158' => '2',
'159' => '1',
'160' => '2',
'161' => '1'
];
where the keys are unique - they don't ever repeat. And the value could be either 1 or 2 - nothing else.
And I need to "split" this $arrayAll array into $array1 - that will contain everything with value 1 and $array2 - that will contain everything with value 2 so in the end I will have:
$array1 = [
'156' => '1',
'157' => '1',
'159' => '1',
'161' => '1'
];
and
$array2 = [
'158' => '2',
'160' => '2'
];
and as you can see, I will have the keys from the original array will remain the same.
What is the simplest thing to do to separate the original array like this?
This is probably the simplest way.
Loop it and create a temporary array to hold the values then extract the values to your array 1 and 2.
Foreach($arrayAll as $k => $v){
$res["array" . $v][$k] = $v;
}
Extract($res);
Var_dump($array1, $array2);
https://3v4l.org/6en6l
Updated to use extract and a method of variable variables.
The update means it will work even if there is a value "3" in the input array.
https://3v4l.org/jbvBf
Use foreach and compare each value and assign it to a new array.
$array1 = [];
$array2 = [];
foreach($arrayAll as $key=>$val){
if($val == 2){
$array2[$key] = $val;
}else{
$array1[$key] = $val;
}
}
print_r($array1);
print_r($array2);
Demo
The simplest thing to do is to use a foreach loop.
$array = [
'156' => '1',
'157' => '1',
'158' => '2',
'159' => '1',
'160' => '2',
'161' => '1'
];
$array1 = [];
$array2 = [];
foreach ($array as $key => $value)
// If value is 1, add to array1
// If value is not 1, add value to array2
if ($value === '1')
$array1[$key] = $value;
else
$array2[$key] = $value;
echo var_dump($array1);
echo '<br>';
echo var_dump($array2);
Use indirect reference:
$arrayAll = array("156"=>"1", "157"=>"1", "158"=>"2", "159"=>"1", "160"=>"2", "161"=>"1");
foreach($arrayAll as $key=>$value) {
$name = "array".$value;
$$name[$key] = $value;
}
echo "<pre>";
print_r($array1);
print_r($array2);
echo "</pre>";
//your array
$yourArray = [
'156' => '1',
'157' => '1',
'158' => '2',
'159' => '1',
'160' => '2',
'161' => '1'
];
With the conditions you mentioned just build two arrays, you can use array_keys with the second parameter that accepts a search value
$array1 = array_keys($yourArray, '1');
$array2 = array_keys($yourArray, '2');
If you don't want to use array_keys, go for an iteration
$array1 = array();
$array2 = array();
foreach($yourArray as $key=>$value){
//will always be 1 or 2, so an if-else is enought
if($value == 1){
$array1[] = $key;
} else {
$array2[] = $key;
}
}
And that's it.
Check this link for array_keys
If you have more than 2 values, the following will work and can be reused for other cases
You want to group them according to the values
$arrayOfValues = array_values($yourArray);
//this returns only the values of the array
$arrayOfUniqueValues = array_unique($arrayOfValues);
//this returns an array with the unique values, also with this u consider
//the posibility for more different values
//also u can get the unique values array on a single line
$arrayIfUniqueValues = array_unique(array_values($yourArray));
The array you will return
$theReturn = array();
foreach($arrayOfUniqueValues as $value ){
//what does this do?
//for each iteration it creates a key in your return array "$theReturn"
//and that one is always equal to the $value of one of the "Unique Values"
//array_keys return the keys of an array, and with the second parameter
//it acceps a search parameter, so the keys it return are the ones
//that matches the value, so here u are getting the array already made
$theReturn[$value] = array_keys($yourArray, $value);
}
The var_dump, in this case, will look like this
array(2) {
[1]=>
array(4) {
[0]=>
int(156)
[1]=>
int(157)
[2]=>
int(159)
[3]=>
int(161)
}
[2]=>
array(2) {
[0]=>
int(158)
[1]=>
int(160)
}
}
Hope my answer helps you, I tried to organize the solutions starting with the shortest/simplest.
Edit:
I forgot you needed the key value too, at least in this solution the array is always referring to the value, like $array1, $array2 or the $key references to the value as in the last solution
The simplest solution for separating an array into others based on the values involves:
Getting its unique values using array_unique.
Looping over these values using foreach.
Getting the key-value pairs intersecting with the current value using array_intersect.
Code:
# Iterate over every value and intersect it with the original array.
foreach(array_unique($arrayAll) as $v) ${"array$v"} = array_intersect($arrayAll, [$v]);
Advantage:
The advantage of this answer when compared to other given answers is the fact that it uses array_unique to find the unique values and therefore iterates only twice instead of n times.
Check out a live demo here.
This question already has answers here:
Compare 2-dimensional data sets based on a specified second level value
(9 answers)
Closed last year.
I have two multidimensional arrays which are indexed arrays of associative rows.
$array1 = array(
array('name' => 'foo', 'id' => 12),
array('name' => 'bar', 'id' => 34),
array('name' => 'boo', 'id' => 56),
);
$array2 = array(
array('name' => 'bar', 'id' => 34),
array('name' => 'boo', 'id' => 56),
array('name' => 'bar', 'id' => 78),
);
It is possible that rows might have different id values but the same name value -- such as bar in my sample input data.
I need to compare the arrays based on id values only.
Expected Output: (because ids 34 and 56 are found in $array2)
array(
array('name' => 'foo', 'id' => 12)
)
I tried $one_not_two = array_diff($array1['id'], $array2['id']); which does not return anything.
I also tried $one_not_two = array_diff($array1['id'], $array2['id']);
which returned an error "argument is not an array."
Originally, I got around it by extracting the ids into a one-dimensional array, then just comparing those. Now a new feature in our application requires me to compare the rows while maintaining the multidimensional structure. Any advice?
Our servers are currently running php 5.3 if that makes any difference.
Because the arrays are multidimensional you have to extract the ids like this:
$ids1 = array();
foreach($array1 as $elem1)
$ids1[] = $elem1['id'];
$ids2 = array();
foreach($array2 as $elem2)
$ids2[] = $elem2['id'];
$one_not_two = array_diff($ids1,$ids2);
For your specific question, check out array_diff() with multidimensional arrays
You could use array_udiff to create a custom diff function:
$diff = array_udiff($array1,
$array2,
function ($a, $b){
if($a['id'] == $b['id']){
return 0;
} else {
return ($a['id'] < $b['id'] ? -1 : 1);
}
}
);
http://codepad.viper-7.com/2u5EWg
If id is unique you can do that:
$one_not_two = array();
foreach ($array1 as $val) {
$one_not_two[$val['id']] = $val;
}
foreach ($array1 as $val) {
if (!isset($one_not_two[$val['id']])) {
$one_not_two[$val['id']] = $val;
}
In the end I solved it by changing Array1 to an associative array of name => id
Having the same problem as you.
Solved it with: $result = array_diff_assoc($array2, $array1);
Reference: PHP: array_diff_assoc
I have an array as the following:
function example() {
/* some stuff here that pushes items with
dynamically created key strings into an array */
return array( // now lets pretend it returns the created array
'firstStringName' => $whatEver,
'secondStringName' => $somethingElse
);
}
$arr = example();
// now I know that $arr contains $arr['firstStringName'];
I need to find out the index of $arr['firstStringName'] so that I am able to loop through array_keys($arr) and return the key string 'firstStringName' by its index. How can I do that?
If you have a value and want to find the key, use array_search() like this:
$arr = array ('first' => 'a', 'second' => 'b', );
$key = array_search ('a', $arr);
$key will now contain the key for value 'a' (that is, 'first').
key($arr);
will return the key value for the current array element
http://uk.php.net/manual/en/function.key.php
If i understand correctly, can't you simply use:
foreach($arr as $key=>$value)
{
echo $key;
}
See PHP manual
If the name's dynamic, then you must have something like
$arr[$key]
which'd mean that $key contains the value of the key.
You can use array_keys() to get ALL the keys of an array, e.g.
$arr = array('a' => 'b', 'c' => 'd')
$x = array_keys($arr);
would give you
$x = array(0 => 'a', 1 => 'c');
Here is another option
$array = [1=>'one', 2=>'two', 3=>'there'];
$array = array_flip($array);
echo $array['one'];
Yes you can infact php is one of the few languages who provide such support..
foreach($arr as $key=>$value)
{
}
if you need to return an array elements with same value, use array_keys() function
$array = array('red' => 1, 'blue' => 1, 'green' => 2);
print_r(array_keys($array, 1));
use array_keys() to get an array of all the unique keys.
Note that an array with named keys like your $arr can also be accessed with numeric indexes, like $arr[0].
http://php.net/manual/en/function.array-keys.php
you can use key function of php to get the key name:
<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array).'<br />';
}
next($array);
}
?>
like here : PHP:key - Manual