Couldn't use integer as a key in associative array PHP - php

I want to use an integer as key in an associative array. I tried using settype() method to convert it to string and then merge it with an existing associative array
Here is the code:
$Xcenter = 325;
$Ycenter = 59.8;
$Xcenter = strval($XCenter);
$existing_array = array('a'=>'b', 'b'=>'c');
$new_array = array($XCenter=>$YCenter);
$result = array_merge($existing_array, $new_array);
print_r($result);
Current Output:
Array ( [a] => b [b] => c [0] => 59.8 )
Expected Output:
Array ( [a] => b [b] => c [325] => 59.8 )
For some reason it is not converting integer to string. But this is working perfectly fine for float values like the one below:
Array ( [a] => b [b] => c [148.33333333333] => 59.8 )

From the manual for array_merge:
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.
If you want to just set a key to a specific value, you don't need to merge, you can just set it like $array[123] = $foo. Or do a union with $array1 + $array2. But just an FYI, a union will not re-index numeric keys and it will not overwrite previous values. So you typically have to reverse the arguments that you would normally pass to array_merge. So array_merge($a1, $a2) is pretty much the same as $a2 + $a1 without the re-indexed numeric keys.

Related

PHP - Store an array returned by a function in an already existing array, one by one

Very simplified example:
function returnArray() {
return array('First','Second','Third');
}
$arr = array('hello','world');
$arr[] = returnArray();
print_r($arr);
I was (wrongly) expecting to see $arr containing 5 elements, but it actually contains this (and I understand it makes sense):
Array
(
[0] => hello
[1] => world
[2] => Array
(
[0] => First
[1] => Second
[2] => Third
)
)
Easily enough, I "fixed" it using a temporary array, scanning through its elements, and adding the elements one by one to the $arr array.
But I guess/hope that there must be a way to tell PHP to add the elements automatically one by one, instead of creating a "child" array within the first one, right? Thanks!
You can use array_merge,
$arr = array_merge($arr, returnArray());
will result in
Array
(
[0] => hello
[1] => world
[2] => First
[3] => Second
[4] => Third
)
This will work smoothly here, since your arrays both have numeric keys. If the keys were strings, you’d had to be more careful (resp. decide if that would be the result you want, or not), because
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.
You are appending the resulting array to previously created array. Instead of the use array merge.
function returnArray() {
return array('First','Second','Third');
}
$arr = array('hello','world');
$arr = array_merge($arr, returnArray());
print_r($arr);

How to compare two arrays and add keys from one array to another

I have two arrays
1st array
first array containts 60 strings like this:
['string1','string2', ... , string60];
2nd array
And I have an associative array like this:
['Key' => value, ..., 'Key' => value]
What I need to do is compare each value from first array(that contains 60 ellements), with each key from the second array, and if second(associative) array doesn't contain key that matches any value from first array - I should add such ellement to the associative array.
For example second array doesn't have key that matches string5 for example, and I'm not talking about value of the key, I'm literally talking about Key itself. So now I need to add string5 as a new key => value ellement to the array, the Key must be the word string5, and the value must be empty.
What is the best way to do it?
Not more complicated than:
$combined = $array2 + array_fill_keys($array1, null);
array_fill_keys creates an array like ['string1' => null, ..], + adds all of these keys which don't already exists in $array2.
$combined = $array2 + array_fill_keys($array1, null);// key value will be maintained
array_values($array2); //index starts from 0
This should work
foreach($array_1 as $val) {
if(!isset($array_2[$val])) {
$array_2[$val] = null;
}
}
pretty sure there are people who know more efficient ways (resource wise) as this might take long when you have huge arrays.
Here is the logical way to do this.
First divide the second array in key and values array. I mean two different array.
So
$keys = array_keys($array2);
$values = array_values($array2);
now you have to take the different from $array1 to $array2 sigular or vice-versa ( Depends on your requirement ) and it will give you the difference of missing keys.
$diff = array_diff($array1,$keys);
Now you will be able to find it easily.
Please refer to array_diff Source: php.net
<?php
$required = array('key1', 'key2', 'key3','key4');
$data = array(
'key1' => 10,
'key2' => 20
);
$arrayDiff = array_diff_key(array_flip($required),$data);
$final = array_merge($data,$arrayDiff);
// Result
// Array
//(
// [key1] => 10
// [key2] => 20
// [key3] => 2
// [key4] => 3
//)
?>
If you want default value to be populated to the new keys added to the array, add below line before merge and use the variable $arrayFill instead of $arrayDiff in the merge statement
$arrayFill = array_fill_keys(array_flip($arrayDiff),0);

Removing duplicates with array_unique giving wrong result

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

Accessing an associative array by integer index in PHP

I want to set the value of an associative array using the array index of the key/value pair. For example:
$my_arr = array( "bling" => "some bling", "bling2" => "lots O bling" );
$my_arr[1] = "not so much bling"; // Would change the value with key bling2.
How can this be accomplish this without using the key string?
Use array_keys.
$keys = array_keys($my_arr);
$my_arr[$keys[1]] = "not so much bling";
There is no correlation between numeric and associative index keys.
When you say you want to set the value of an associative array using the array index of the key/value, then you have to use the given key, setting $array[1] is not the same as setting $array['foo'].
Consider this array
print_r( array('foo', 'foo' => 'bar', 'baz', 'some' => 'value') );
This will give
Array
(
[0] => foo
[foo] => bar
[1] => baz
[some] => value
)
The foo is the second element in the array. That's the offset, but it has nothing to do with the index 1. As you can see, in that array above, index 1 is associated with baz. It is wrong to assume that just because foo is the first associative key it has anything to do with the actual numeric key 1. Just like some does not correlate to 2.
Likewise, for a mixed array like shown above, the solution with array_keys suggested elsewhere on this site will not work, because
print_r( array_keys(array('foo', 'foo' => 'bar', 'baz', 'some' => 'value')) );
will give
Array
(
[0] => 0
[1] => foo
[2] => 1
[3] => some
)
So when you do $array[$keys[1]] you are really doing $array['foo']. But if you wanted to access the second associative value in that array ('some'), you cannot do $array[$keys[2]] because that would evaluate to $array[1] and that's baz.
The Offset of an element is completely unrelated to it's key or value
print_r(
array(
100 => 'foo',
'foo' => 'bar',
50 => 'baz',
'some' => 'value'
)
);
really means
Array
( //key value offset/position
[100] => foo // 0
[foo] => bar // 1
[50] => baz // 2
[some] => value // 3
)
which means the element at offset 0 is foo although it's key is 100. If you want to extract elements from an array by offset, you have to use
$third = array_splice($array, 2, 1);
echo $third[0]; // baz
This would create an array holding only the element at the third position.
Or you could use an ArrayIterator. The ArrayIterator implements a Seekable interface that lets you seek to a specific position/offset in the array and then fetch that:
$iterator = new ArrayIterator($array);
$iterator->seek(3);
echo $iterator->current(); // value
Whilst array_keys() allows access to the nth key, array_values will give you the nth value.
<?php
$array = [
0 => 'Zero',
'1' => 'One',
'Two' => 'Two',
];
echo array_values($array)[2];
?>
will output 'Two'.
Is there an advantage of one over the other? Well, the only minor one I can see is the number of array accesses.
With array_keys() you need to 3.
Get the keys from the data array.
Get the nth key from the list of keys.
Get the value using the nth key from the data array.
With array_values(), you only need 2.
Get the values from the data array.
Get the nth value from the list of values.
But, on the other hand, keys are normally smaller and the data could be hugely nested, so, on balance, using the array_keys() is probably safer.
If the array is large, both array_keys and array_values will be wasteful since they will allocate a new array the same size as the original, just to get the nth key (or value).
array_slice accepts an integer offset and works on associative arrays. You can use it to get (and set) the nth key in constant time.
// This will at most allocate 2 temporary arrays of 1 element each
$key = array_keys(array_slice($array, $n, 1, true))[0];
$array[$key] = $value;
Try this. It works for you.
$result= array_values($my_arr); // Array with indexes you need
Another possibility is to convert it to a normal array:
$arraybuff = implode("~~~",$my_arr);
$my_arr = explode("~~~",$arraybuff);
Where "~~~" is a delimiter that wont occur in your data.
Now you can access the array using numerical indexes equal to the offsets.
If you still need to retain your associative array, just assign it to a different variable.

php assoc array

I have two assoc array i want to creat one array out of that
E.g
a(a=>1
b=>3
f=>5
)
b(a=>4
e=>7
f=>9
)
output must be
c(
a=>1
b=>3
f=>5
a=>4
e=>7
f=>9
)
i am new in php
Use array_merge(). Your resulting array CAN NOT have more than one entry for the same key, so the second a => something will overwrite the first.
Use the + operator to return the union of two arrays.
The new array is constructed from the left argument first, so $a + $b takes the elements of $a and then merges the elements of $b with them without overwriting duplicated keys. If the keys are numeric, then the second array is just appended.
This ey difference of the + operator and the function, array_merge is that array merge overwrites duplicated keys if the latter arguments contain that key. The documentation puts it better:
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 the keys are different, then use array_merge()
<?php
$a1=array("a"=>"Horse","b"=>"Cat");
$a2=array("c"=>"Cow");
print_r(array_merge($a1,$a2));
?>
OUTPUT:
Array ( [a] => Horse [b] => Cat [c] => Cow )
If the keys are the same, then use array_merge_recursive()
<?php
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?>
OUTPUT:
Array
(
[color] => Array
(
[favorite] => Array
(
[0] => red
[1] => green
)
[0] => blue
)
[0] => 5
[1] => 10
)

Categories