Im curious to know if php has a function that allows me to connect 2 arrays together and replace values from array1 with values of array2 if the values from array2 already exist. see example
array1('value1','value2','value3',);
array2('value4','value2','value1');
array3 = functionEmerge(array1, array2);
array3('value1','value2','value3','value4',);
You could call array_unique() on the result of array_merge() to get your desired result.
I believe you are talking about taking the union of two arrays. If that's the case, PHP comes with the union array operator, which is just +. So:
$arr = array('value1', 'value2', 'value3') + array('value1', 'value2', 'value4');
Should get you:
array('value1', 'value2', 'value3', 'value4')
I could be wrong, so test this before you use it.
the function you're looking for is called array_merge
array array_merge ( array $array1 [, array $array2 [, array $... ]] )
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
If only one array is given and the array is numerically indexed, the keys get reindexed in a continuous way.
I didn't find a single operator for that, but this will work:
$array3 = array_keys(array_flip($array1) + array_flip($array2))
Set::merge( $a, $b )
Related
I have two arrays :
$array1 = [460,471];
$array2 = [193,42,471];
I want to take the value only in $array1 if there is no same value in $array2, if there is a same value in $array2 filter it out.
Expected output if no same value available in $array2:
$output = [460, 471]
Expected output is there is same value in $array2:
$output = [460]
Try array_diff() function
$array1 = [460,471];
$array2 = [193,42,471];
$filtered = array_diff($array1,$array2);
print_r($filtered);
You can achieve the same with the help of Hashing pretty easily.
First, try to map the values of array2 into a Hash.
For example, each element of $array2 = [193,42,471]; will have a value marking their presence as true.
Now, for each element is $array1, check if it has a value in the Hash. If it has one, then skip it.
So after the check, you will get all the values that are not present in the second array.
I need to merge the second array into the first. For example the first array is
$data_array = array
(
array('Ford','Escape','25000','new')
);
The second array is
$new_array = array
(
array('Toyota','Camry','12000','used')
);
For merging the two arrays I tried
$data_array = array_merge($data_array[0],$new_array[0]);
print_r($data_array);
This combines the two arrays into one row array. What I want is to create two rows, each containing one of those arrays.
Sample result:
array(array('Ford','Escape','25000','new'),array('Toyota','Camry','12000','used'))
You have to assign the merged result. Pay attention to the function signature and description in the manual for array_merge():
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
$merged_array = array_merge($data_array[0],$new_array[0]);
print_r($merged_array);
You could call it $data_array and overwrite the existing one:
$data_array = array_merge($data_array[0],$new_array[0]);
print_r($data_array);
Or even $data_array[0]:
$data_array[0] = array_merge($data_array[0],$new_array[0]);
print_r($data_array);
Contrast this with something like sort():
bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
Where the bool means that it returns true or false and the & preceding $array means that the array is passed by reference and modified.
However, after your edit it seems that you want the two rows in your original arrays to be two rows in a new array, so just don't specify the index [0]:
$data_array = array_merge($data_array,$new_array);
print_r($data_array);
In my code I need to make a number of copies of a dummy array. The array is simple, for example $dummy = array('val'=> 0). I would like make N copies of this array and tack them on to the end of an existing array that has a similar structure. Obviously this could be done with a for loop but for readability, I'm wondering if there are any built in functions that would make this more verbose.
Here's the code I came up with using a for loop:
//example data, not real code
$existingArray = array([0] => array('val'=>2),[1] => array('val'=>3) );
$n = 2;
for($i=0;$i<$n;$i++) {
$dummy = array('val'=>0); //make a new array
$existingArray[] = $dummy; //add it to the end of $existingArray
}
To reiterate, I'd like to rewrite this with functions if such functions exist. Something along the lines of this (obviously these are not real functions):
//make $n copies of the array
$newvals = clone(array('val'=>0), $n);
//tack the new arrays on the end of the existing array
append($newvals, $existingArray)
I think you're looking for array_fill:
array array_fill ( int $start_index , int $num , mixed $value )
Fills an array with num entries of the value of the value parameter, keys starting at the start_index parameter.
So:
$newElements = array_fill(0, $n, Array('val' => 0));
You do still have to handle the appending of $newElements to $existingArray yourself, probably with array_merge:
array array_merge ( array $array1 [, array $... ] )
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
So:
$existingArray = array_merge($existingArray, $newElements);
This all works because your top-level arrays are numerically-indexed.
I have two arrays, like this:
$array1 = array(
'ADAIR',
'ADAM',
'ADAMINA',
'ADDISON',
'ADDY',
'ADELLE',
'ADEN',
'ADOLPH',
'ADRIANNA'
);
$array2 = array(
'ADAIR',
'ADAMINA',
'ADRIANNA'
);
How do I make a third array, without duplicates? We should take first array and remove from it duplicates from second array.
Use Array-diff
$array3=array_diff($array1,$array2);
Returns an array containing all the entries from array1 that are not present in any of the other arrays.
Take a look here: http://php.net/manual/en/function.array-unique.php
Combine both arrays into 1, then run them through the array-unique function
$result = array_unique($combined);
#grunk deleted a perferctly valid answer, so credits not to me:
$unique = array_unique(array_merge($array1,$array2));
codepad.org/NVkuml5g
Is it possible to prepend an associative array with literal key=>value pairs? I know that array_unshift() works with numerical keys, but I'm hoping for something that will work with literal keys.
As an example I'd like to do the following:
$array1 = array('fruit3'=>'apple', 'fruit4'=>'orange');
$array2 = array('fruit1'=>'cherry', 'fruit2'=>'blueberry');
// prepend magic
$resulting_array = ('fruit1'=>'cherry',
'fruit2'=>'blueberry',
'fruit3'=>'apple',
'fruit4'=>'orange');
Can't you just do:
$resulting_array = $array2 + $array1;
?
You cannot directly prepend an associative array with a key-value pair.
However, you can create a new array that contains the new key-value pair at the beginning of the array with the union operator +. The outcome is an entirely new array though and creating the new array has O(n) complexity.
The syntax is below.
$new_array = array('new_key' => 'value') + $original_array;
Note: Do not use array_merge(). array_merge() overwrites keys and does not preserve numeric keys.
In your situation, you want to use array_merge():
array_merge(array('fruit1'=>'cherry', 'fruit2'=>'blueberry'), array('fruit3'=>'apple', 'fruit4'=>'orange'));
To prepend a single value, for an associative array, instead of array_unshift(), again use array_merge():
array_merge(array($key => $value), $myarray);
Using the same method as #mvpetrovich, you can use the shorthand version of an array to shorten the syntax.
$_array = array_merge(["key1" => "key_value"], $_old_array);
References:
PHP: array_merge()
PHP: Arrays - Manual
As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].
#Cletus is spot on. Just to add, if the ordering of the elements in the input arrays are ambiguous, and you need the final array to be sorted, you might want to ksort:
$resulting_array = $array1 + $array2;
ksort($resulting_array);
If using Laravel, you can use prepend on a collection instance
collect(['b' => 'b', 'c' => 'c'])->prepend('a','a');
// ['a'=>'a', 'b' => 'b', 'c' => 'c']
https://laravel.com/docs/9.x/collections#method-prepend