I have two dynamic associated array and I am trying to merge them into one array BUT I need to keep the original keys as the orginal arrays but in return I am getting [0] for A which I need to keep it [1] as it was in array $a
$a = ["1"=>"A", "2"=>"B", "3"=>"C"];
$b = ["n"=>"5"];
$c = array_merge($a,$b);
print_r($c);
Array (
[0] => A
[1] => B
[2] => C
[n] => 5 )
In order to preserve keys of your array you need to use + operator over here like as
$a = ["1"=>"A", "2"=>"B", "3"=>"C"];
$b = ["n"=>"5"];
$c = $a + $b;
print_r($c);
You can check PHP Manuals Example #2 Simple array_merge() example
i am not a php developer. so there could be better answers out there
the php documentation says that numerical keys are new numbered. i think that even a string as key with a nummeric value is interpretet as number.
can you try this (not the added 'a' on the nummeric keys):
$a = ["1a"=>"A", "2a"=>"B", "3a"=>"C"];
$b = ["n"=>"5"];
$c = array_merge($a,$b);
print_r($c);
it is not clean code, but after this you can "remove" the 'a' and you have your numeric key
Related
I've got two arrays of the same size. I'd like to merge the two so the values of one are the key indexes of the new array, and the values of the new array are the values of the other.
Right now I'm just looping through the arrays and creating the new array manually, but I have a feeling there is a much more elegant way to go about this. I don't see any array functions for this purpose, but maybe I missed something? Is there a simple way to this along these lines?
$mapped_array = mapkeys($array_with_keys, $array_with_values);
See array_combine() on PHP.net.
(from the docs for easy reading)
array_combine — Creates an array by using one array for keys and another for its values
Description
array array_combine ( array $keys , array $values )
Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.
Parameters
keys - Array of keys to be used. Illegal values for key will be converted to string.
values - Array of values to be used
Example
<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);
print_r($c);
?>
The above example will output:
Array
(
[green] => avocado
[red] => apple
[yellow] => banana
)
This should do the trick
function array_merge_keys($ray1, $ray2) {
$keys = array_merge(array_keys($ray1), array_keys($ray2));
$vals = array_merge($ray1, $ray2);
return array_combine($keys, $vals);
}
I have comma separated values in my table column and I have to separate new values from the old ones.
My code is
$a = '1,2,3,4';
$b = '1,2';
if(preg_match("/[^$b]/",$a,$matches)){
print_r($matches);
};
I want to find 3,4 , but I can't do it.
You really shouldn't use regular expressions for that. PHP has good functions to calculate intersections:
$a = explode(',', '1,2,3,4');
$b = explode(',', '1,2');
print_r(array_values(array_diff($a, $b)));
See also: array_diff()
Note that this would also work for the following example:
$a = '1,2,3,4';
$b = '1,3';
// outcome must be: 2, 4
use preg_match_all instead of preg_match
$a = '1,2,3,4,10';
$b = '1,2';
if(preg_match_all("/[^$b](.*)/",$a,$matches)){
print_r($matches);
};
output
Array
(
[0] => Array
(
[0] => 3,4,10
)
[1] => Array
(
[0] => ,4,10
)
)
i have two array and i want to make unique array with single array
for example i have $a=array(3); and $b=array(1,2,3) so i want $c=array(1,2,3)
i made a code like:
$a=array(3);
$b=explode(',','1,2,3');
$ab=$a+$b;
$c=array_unique ($ab);
print_r($c);
it gives me Array ( [0] => 3 [1] => 2 )
but i want to Array ( [0] => 1 [1] => 2 [2] => 3 )
$a = array(1,2,3,4,5,6);
$b = array(6,7,8,2,3);
$c = array_merge($a, $b);
$c = array_unique($c);
The operation
$ab = $a + $b
Is giving you a result you did not expect. The reason for this behaviour has been explained previously at PHP: Adding arrays together
$ab is Array ( [0] => 3 [1] => 2 [2] => 3 )
The + operator appends elements of remaining keys from the right
handed array to the left handed, whereas duplicated keys are NOT
overwritten.
array_merge provides a more intuitive behaviour.
Array merge, man. Array merge.
Anyway, as this answer for similar question ( https://stackoverflow.com/a/2811849/223668 ) tells us:
The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten.
If you have numeric keys (as in standard tables), they are for for sure duplicate in both arrays and the result is far from desired.
So the code should look like that:
$c = array_unique(array_merge($a, $b));
You need to use this array_merge to concat two array.
http://www.php.net/manual/en/function.array-merge.php
not
$ab = $a + $b
I've noticed recently in PHP you can do this.
$myNewArray = $oldArray + $someArray;
This looks completely different to anything I've seen before involving manipulating arrays in PHP.
How and why does it work? Are there any pitfalls?
I have recently started using it in some places where I may have used array_unshift() and array_merge().
When in doubt, consult the documentation. The behavior is different from array_merge: array_merge appends/overwrites, + only appends.
Example:
<?php
$a = Array('foo'=>'bar','baz'=>'quux');
$b = Array('foo'=>'something else','xyzzy'=>'aaaa');
$c = $a + $b;
$d = array_merge($a,$b);
print_r($c);
print_r($d);
Output - as you see, array_merge overwrote the value from $a['foo'] with $b['foo']; $a+$b did not:
Array
(
[foo] => bar
[baz] => quux
[xyzzy] => aaaa
)
Array
(
[foo] => something else
[baz] => quux
[xyzzy] => aaaa
)
An operation is defined in the compiler for + when both operands are arrays. It does the intuitive operation of joining them.
One of the pitfalls is what happens when one of the variables is not an array.
array_merge:
Warning: array_merge(): Argument #2 is not an array in ...
+-operator:
Fatal error: Unsupported operand types in ...
I want to sort values of an array in alphabetical order in PHP. If all values started with same character then they should be sorted using second character and so on. Ignore case sensitive.
For Example:
before:
values[0] = "programming";
values[1] = "Stackoverflow";
values[2] = "question";
values[3] = "answers";
values[4] = "AA Systems";
after:
values[0] = "AA Systems";
values[1] = "answers";
values[2] = "programming";
values[3] = "question";
values[4] = "Stackoverflow";
I have found some algorithms but I want a way that is fast and with small number of statements. Ignoring case sensitive is special for me. Thanks.
See
natcasesort: http://www.php.net/manual/en/function.natcasesort.php
usort: http://www.php.net/manual/en/function.usort.php with a comparator function that compares strtolower(a) and strtolower(b).
Your example makes two assumptions:
That you are only dealing with simple, 1-dimensional arrays.
That after sorting alphabetically, your index will update so that the first element alphabetically will be assigned key 0 and so forth.
Given those parameters, your simplest solution is to use the array method sort(). With your example:
$values[0] = "programming";
$values[1] = "Stackoverflow";
$values[2] = "question";
$values[3] = "answers";
$values[4] = "AA Systems";
sort($values);
Which will result in the following:
Array {
[0] => AA Systems
[1] => Stackoverflow
[2] => answers
[3] => programming
[4] => question
}
There are other array sorting functions that might be a better fit. For instance, the simple one I use above puts upper-case in front of lower-case, so if you had "security" as an item (all lower-case) it would go after "Stackoverflow" since the upper-case s would take precedence over se vs. st. To sort without case-sensitivity, you could use natcasesort(), which would produce the following with the given array:
Array {
[0] => AA Systems
[1] => answers
[2] => programming
[3] => question
[4] => Stackoverflow
}
As of version 5.4.0, you can just use any of the sort, asort, ksort, etc. functions and pass the SORT_FLAG_CASE flag.
sort( $array, SORT_FLAG_CASE ); // Non-associative array
asort( $array, SORT_FLAG_CASE ); // Associative array
ksort( $array, SORT_FLAG_CASE ); // Associative array, sort by indices
If you've got an older version and aren't ready to update (or can't), you can use natcasesort as others have mentioned, but also the uasort and ksort variants with strcasecmp as the custom function:
natcasesort( $array ); // Non-associative array
uasort( $array, 'strcasecmp' ); // Associative array
uksort( $array, 'strcasecmp' ); // Associative array, sort by indices
You can apply the same concept to any of the other sorting functions.
You can use uasort(): http://php.net/manual/en/function.uasort.php
uasort( $arr, 'strcasecmp' );
The second argument is a function, which compares values. The function must return -1, 0, or 1. Here's a template, which you can use for your custom functions.
function cmp( $a, $b ) {
if ( $a == $b ) return 0;
elseif ( $a > $b ) return 1;
elseif ( $a < $b ) return -1;
}
uasort( $arr, 'cmp' );
After sorting you might want to reset array indexes.
$arr = array_values( $arr );