I have an associative array, which keys I want to use in numbers. What I mean: The array is kinda like this:
$countries = array
"AD" => array("AND", "Andorra"),
"BG" => array("BGR", "Bulgaria")
);
Obviously AD is 0 and BG is 1, but when I print $countries[1] it doesn't display even "Array".
When I print $countries[1][0] it also doesn't display anything. I have the number of the key, but I shouldn't use the associative key.
Perfect use case for array_values:
$countries = array_values($countries);
Then you can retrieve the values by their index:
$countries[0][0]; // "AND"
$countries[0][1]; // "Andorra"
$countries[1][0]; // "BGR"
$countries[1][1]; // "Bulgaria"
array_keys() will give you the array's keys. array_values() will give you the array's values. Both will be indexed numerically.
you might convert it into a numeric array:
$countries = array(
"AD" => array("AND", "Andorra"),
"BG" => array("BGR", "Bulgaria")
);
$con=array();
$i=0;
foreach($countries as $key => $value){
$con[$i]=$value;
$i++;
}
echo $con[1][1];
//the result is Bulgaria
There are a couple of workarounds to get what you want. Besides crafting a secondary key-map array, injecting references, or an ArrayAccess abomination that holds numeric and associative keys at the same time, you could also use this:
print current(array_slice( current(array_slice($countries, 1)), 0));
That's the fugly workaround to $countries[1][0]. Note that array keys appear to appear in the same order still; bemusing.
Related
I have a quick question. When building an associative array key casting rules mean that strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. (On the other hand "08" will not be cast, as it isn't a valid decimal integer.) See for example: http://php.net/manual/en/language.types.array.php
The problem I have is that my keys are mixed integer and string .. meaning that when the associative array is built, all keys are reordered with numerical keys appear first before string. This is a sample of what I get in my console log:
...
2032: "9371.84"
2033: "9351.60"
2034: "9331.36"
2035: "9311.12"
ID: "1"
Misc1: "Russian Federation - Conventional"
Misc2: "RUS.Con1"
Misc3: "4"
Misc4: ""
... etc.
How can I avoid this issue, so that the associative array does not re-order my keys?
As an FYI, this is how I generate my array in PHP:
while ($array = mysqli_fetch_assoc($result)) {
$experiment[] = $array;
};
Thank you for your time,
G.
Adding an index to an array in PHP like this:
$array[] = ['another array'];
Will increment the indexes.
You can however specify a string for the key, or cast the integers to strings.
The workaround for the issue I have found is to avoid the associative array structure. This is what my loop looks like now:
while ($array = mysqli_fetch_assoc($result)) {
$experiment[0] = array_keys($array);
$experiment[] = array_values($array);
};
The annoying thing is that $experiment[0] = array_keys($array); gets looped uneccessarily... but at least I get the result that I am looking for and the keys are not cast and re-ordered by the associative array.
If anybody knows how to avoid the unecessary looping for $experiment[0], then please let me know :-)
I have a comma separated string which i explode into an array. If the array is of un-known length and i want to make it into a key value pair array where each element in the array has the same key, how do i do this? i'm assuming i'd have to use array_combine? can anyone give me an example using the array bellow? :
for instance:
array([0]=>zebra, [1]=>cow, [2]=>dog, [3]=>monkey, [4]=>ape)
into:
array([animal]=>zebra, [animal]=>cow, [animal]=>dog, [animal]=>monkey, [animal]=>ape)
You can't use the same key for each element in your array. You need a unique identifier to access the value of the array. When you use animal for all, what value should be used? What you can do is to make a 2 dimensional array that you have an array inside an array:
array(
[animals] => array(
[0]=>zebra, [1]=>cow, [2]=>dog, [3]=>monkey, [4]=>ape
)
)
this can be used with $array['animals'][0]
But still you need numbers or unique identifiers to access the values of the array.
Something like this:
$string = 'zebra,cow,dog,monkey,ape';
$array = explode(',', $string);
$arrayReturn['animals'] = $array;
print_r($arrayReturn);
u cant have same key for all the values but u can do this
lets say your string is
$a = 'dog,ant,rabbit,lion';
$ar = explode(',',$a);
$yourArray = array();
foreach($ar as $animals){
$yourArray['animals']=$animals;
}
Now it doesnot matter how long your string is you will have you array as
$yourArray['animals'][0]='dog'
$yourArray['animals'][1]='ant'
....... so on ......
If I have an associative array like this
$array = array();
$array['e01'] = '03/16/2012';
$array['e02'] = '03/14/2012';
$array['e05'] = '03/01/2014';
I'd like to sort the array by date then loop through the results to get the value of the index, i.e. e01, e02, e05. I need that index to retrieve information from an object.
Try uasort() to sort your array:
function mysort($a, $b) {
return (strtotime($a) < strtotime($b)) ? -1 : 1;
}
uasort($array, 'mysort');
For getting the keys you can just use array_keys()
When sorting an associative array, the keys and values change order but the key to value association will not change. So if key e01 has a value of 03/16/2012, even after a uasort (which is probably what you are looking for, see Crashspeeder's answer) e01 will still have the value 03/16/2012. If you want to change the order of the values while keeping the order of the keys:
use array_keys to get the current order of the keys
use usort (no need for uasort as we aren't preserving the keys) to sort the values by date
use array_combine to make a new array with the keys and values.
From the PHP documentation on asort(). This will sort it by value and let you access the key and value of each index:
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
Use the array_keys function.
I am successfully using the array_key_exists(), as described by php.net
Example:
<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>
But, take out the values, and it doesn't work.
<?php
$search_array = array('first', 'second');
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>
Not sure how to only compare 2 arrays by their keys only.
The first example is an associative array: keys with values assigned. The second example is just a prettier way of saying:
array(0 => 'first', 1 => 'second')
For the second, you would need to use in_array. You shouldn't check for the presence of a key, which array_key_exists does, but rather the presence of a value, which in_array does.
if(in_array('first', $array))
In PHP, each element in a array has two parts: the key and the value.
Unless you manually say what keys you want attached to each value, PHP gives each element a numerical index starting at 0, incrementing by 1.
So the difference between
array('first','second')
and
array('first'=>1,'second'=>4)
is that the first doesn't have user-defined keys. (It actually has the keys 0 and 1)
If you were to do print_r() on the first, it would say something like
Array {
[0] => "first",
[1] => "second"
}
whereas the second would look like
Array {
["first"] => 1,
["second"] => 2
}
So, to check if the key "first" exists, you would use
array_key_exists('first',$search_array);
to check if the the value "first" exists, you would use
in_array('first',$search_array);
in the second example, you didn't assign array keys - you just set up a basic "list" of objects
use in_array("first", $search_array); to check if a value is in a regular array
In your second example the keys are numeric your $search_array actually looks like this:
array(0=>'first', 1=>'second');
so they key 'first' doesnt exist, the value 'first' does. so
in_array('first', $search_array);
is the function you would want to use.
In PHP, if you are not giving key to array element they take default key value.Here you arrray will be internally as bellow
$search_array = array(0=>'first', 1=>'second');
Anyway you can still fix this problem by using the array_flip function as below.
$search_array = array('first', 'second');
if (array_key_exists('first', array_flip($search_array))) {
echo "The 'first' element is in the array";
}
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