You can easily get an array value by its key like so: $value = array[$key] but what if I have the value and I want its key. What's the best way to get it?
You could use array_search() to find the first matching key.
From the manual:
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
You can use the array_keys function for that.
Example:
$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));
This will get the key from the array for value blue
$arr = array('mango', 'orange', 'banana');
$a = array_flip($arr);
$key = $a['orange'];
No really easy way. Loop through the keys until you find array[$key] == $value
If you do this often, create a reverse array/hash that maps values back to keys. Keep in mind multiple keys may map to a single value.
Your array values can be duplicates so it wont give you exact keys. However the way i think is fine is like iterate over and read the keys
Related
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
As far as I know array_rand() can only grab a radnom array from an array like this:
$array = array( 'apple', 'orange', 'banana' );
$two_random_items = array_rand( $array , 2 ); // outputs i.e. orange and banana
But how can I grab 2 random items but with the key value array? Like this?
$array = array( '0' => 'apple', '1' => 'orange', '2' => 'banana' );
$rand_keys = array_rand($array, 2);
$rand_values = array();
foreach ($rand_keys as $key) {
$rand_values[] .= $array[$key];
}
That's probably not the right way and it's a lot of code.
I have a big array this is just an example and I need to grab 1000+ or more items randomly from the parent array and put them in a new array, keys can be reset, this is not important. The value part has to stay the same, of course.
Is there a better way how to achieve this?
Just shuffle and slice 2:
shuffle($array);
$rand_values = array_slice($array, 0, 2);
First, this line: $rand_values[] .= $array[$key]; is wrong. The .= operator is to join strings, to add a value to the end of the array, you just need $rand_values[] = $array[$key];.
If you don't care about the keys, just use array_values function to "dump" the keys.
$array = array('a' => 'orange', 'c' => 'banana', 'b' => 'peach');
$two_random_items = array_rand(array_values($array) , 2 );
array_values will strip down the keys, and will return an array with the values (the keys will become 0, 1, 2...)
You can easily get an array value by its key like so: $value = array[$key] but what if I have the value and I want its key. What's the best way to get it?
You could use array_search() to find the first matching key.
From the manual:
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
You can use the array_keys function for that.
Example:
$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));
This will get the key from the array for value blue
$arr = array('mango', 'orange', 'banana');
$a = array_flip($arr);
$key = $a['orange'];
No really easy way. Loop through the keys until you find array[$key] == $value
If you do this often, create a reverse array/hash that maps values back to keys. Keep in mind multiple keys may map to a single value.
Your array values can be duplicates so it wont give you exact keys. However the way i think is fine is like iterate over and read the keys
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
Consider the following array
$array = array('fruit' => 'apple',
'vegetable' => 'potato',
'dairy' => 'cheese');
I wanted to use array_pop to get the last key/value pair.
However, one will note that after the following
$last = array_pop($array);
var_dump($last);
It will output only the value (string(6) "cheese")
How can I "pop" the last pair from the array, preserving the key/value array structure?
Check out array_slice() http://php.net/manual/en/function.array-slice.php
Last argument true is to preserve keys.
When you pass the offset as negative, it starts from the end. It's a nice trick to get last elements without counting the total.
$array = [
"a" => 1,
"b" => 2,
"c" => 3,
];
$lastElementWithKey = array_slice($array, -1, 1, true);
print_r($lastElementWithKey);
Outputs:
Array
(
[c] => 3
)
try
end($array); //pointer to end
each($array); //get pair
You can use end() and key() to the the key and the value, then you can pop the value.
$array = array('fruit' => 'apple', 'vegetable' => 'potato', 'dairy' => 'cheese');
$val = end($array); // 'cheese'
// Moves array pointer to end
$key = key($array); // 'dairy'
// Gets key at current array position
array_pop($array); // Removes the element
// Resets array pointer
Why not using new features? The following code works as of PHP 7.3:
// As simple as is!
$lastPair = [array_key_last($array) => array_pop($array)];
The code above is neat and efficient (as I tested, it's about 20% faster than array_slice() + array_pop() for an array with 10000 elements; and the reason is that array_key_last() is really fast). This way the last value will also be removed.
Tip: You can also extract key and value separately:
[$key, $value] = [array_key_last($array), array_pop($array)];
This should work, just don't do it inside a foreach loop (it'll mess up the loop)
end($array); // set the array pointer to the end
$keyvaluepair = each($array); // read the key/value
reset($array); // for good measure
Edit: Briedis suggests array_slice() which is probably a better solution
Another option:
<?php
end($array);
list($key, $value) = each($array);
array_pop($array);
var_dump($key, $value);
?>
Try this:
<?php
function array_end($array)
{
$val = end($array);
return array(array_search($val, $array) => $val);
}
$array = array(
'fruit' => 'apple',
'vegetable' => 'potato',
'dairy' => 'cheese'
);
echo "<pre>";
print_r(array_end($array));
?>
Output:
Array
(
[dairy] => cheese
)