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
Related
I am searching for a built in php function that takes array of keys as input and returns me corresponding values.
for e.g. I have a following array
$arr = array("key1"=>100, "key2"=>200, "key3"=>300, 'key4'=>400);
and I need values for the keys key2 and key4 so I have another array("key2", "key4")
I need a function that takes this array and first array as inputs and provide me values in response. So response will be array(200, 400)
I think you are searching for array_intersect_key. Example:
array_intersect_key(array('a' => 1, 'b' => 3, 'c' => 5),
array_flip(array('a', 'c')));
Would return:
array('a' => 1, 'c' => 5);
You may use array('a' => '', 'c' => '') instead of array_flip(...) if you want to have a little simpler code.
Note the array keys are preserved. You should use array_values afterwards if you need a sequential array.
An alternative answer:
$keys = array("key2", "key4");
return array_map(function($x) use ($arr) { return $arr[$x]; }, $keys);
foreach($input_arr as $key) {
$output_arr[] = $mapping[$key];
}
This will result in $output_arr having the values corresponding to a list of keys in $input_arr, based on the key->value mapping in $mapping. If you want, you could wrap it in a function:
function get_values_for_keys($mapping, $keys) {
foreach($keys as $key) {
$output_arr[] = $mapping[$key];
}
return $output_arr;
}
Then you would just call it like so:
$a = array('a' => 1, 'b' => 2, 'c' => 3);
$values = get_values_for_keys($a, array('a', 'c'));
// $values is now array(1, 3)
I have this array:
$arrayAll = [
'156' => '1',
'157' => '1',
'158' => '2',
'159' => '1',
'160' => '2',
'161' => '1'
];
where the keys are unique - they don't ever repeat. And the value could be either 1 or 2 - nothing else.
And I need to "split" this $arrayAll array into $array1 - that will contain everything with value 1 and $array2 - that will contain everything with value 2 so in the end I will have:
$array1 = [
'156' => '1',
'157' => '1',
'159' => '1',
'161' => '1'
];
and
$array2 = [
'158' => '2',
'160' => '2'
];
and as you can see, I will have the keys from the original array will remain the same.
What is the simplest thing to do to separate the original array like this?
This is probably the simplest way.
Loop it and create a temporary array to hold the values then extract the values to your array 1 and 2.
Foreach($arrayAll as $k => $v){
$res["array" . $v][$k] = $v;
}
Extract($res);
Var_dump($array1, $array2);
https://3v4l.org/6en6l
Updated to use extract and a method of variable variables.
The update means it will work even if there is a value "3" in the input array.
https://3v4l.org/jbvBf
Use foreach and compare each value and assign it to a new array.
$array1 = [];
$array2 = [];
foreach($arrayAll as $key=>$val){
if($val == 2){
$array2[$key] = $val;
}else{
$array1[$key] = $val;
}
}
print_r($array1);
print_r($array2);
Demo
The simplest thing to do is to use a foreach loop.
$array = [
'156' => '1',
'157' => '1',
'158' => '2',
'159' => '1',
'160' => '2',
'161' => '1'
];
$array1 = [];
$array2 = [];
foreach ($array as $key => $value)
// If value is 1, add to array1
// If value is not 1, add value to array2
if ($value === '1')
$array1[$key] = $value;
else
$array2[$key] = $value;
echo var_dump($array1);
echo '<br>';
echo var_dump($array2);
Use indirect reference:
$arrayAll = array("156"=>"1", "157"=>"1", "158"=>"2", "159"=>"1", "160"=>"2", "161"=>"1");
foreach($arrayAll as $key=>$value) {
$name = "array".$value;
$$name[$key] = $value;
}
echo "<pre>";
print_r($array1);
print_r($array2);
echo "</pre>";
//your array
$yourArray = [
'156' => '1',
'157' => '1',
'158' => '2',
'159' => '1',
'160' => '2',
'161' => '1'
];
With the conditions you mentioned just build two arrays, you can use array_keys with the second parameter that accepts a search value
$array1 = array_keys($yourArray, '1');
$array2 = array_keys($yourArray, '2');
If you don't want to use array_keys, go for an iteration
$array1 = array();
$array2 = array();
foreach($yourArray as $key=>$value){
//will always be 1 or 2, so an if-else is enought
if($value == 1){
$array1[] = $key;
} else {
$array2[] = $key;
}
}
And that's it.
Check this link for array_keys
If you have more than 2 values, the following will work and can be reused for other cases
You want to group them according to the values
$arrayOfValues = array_values($yourArray);
//this returns only the values of the array
$arrayOfUniqueValues = array_unique($arrayOfValues);
//this returns an array with the unique values, also with this u consider
//the posibility for more different values
//also u can get the unique values array on a single line
$arrayIfUniqueValues = array_unique(array_values($yourArray));
The array you will return
$theReturn = array();
foreach($arrayOfUniqueValues as $value ){
//what does this do?
//for each iteration it creates a key in your return array "$theReturn"
//and that one is always equal to the $value of one of the "Unique Values"
//array_keys return the keys of an array, and with the second parameter
//it acceps a search parameter, so the keys it return are the ones
//that matches the value, so here u are getting the array already made
$theReturn[$value] = array_keys($yourArray, $value);
}
The var_dump, in this case, will look like this
array(2) {
[1]=>
array(4) {
[0]=>
int(156)
[1]=>
int(157)
[2]=>
int(159)
[3]=>
int(161)
}
[2]=>
array(2) {
[0]=>
int(158)
[1]=>
int(160)
}
}
Hope my answer helps you, I tried to organize the solutions starting with the shortest/simplest.
Edit:
I forgot you needed the key value too, at least in this solution the array is always referring to the value, like $array1, $array2 or the $key references to the value as in the last solution
The simplest solution for separating an array into others based on the values involves:
Getting its unique values using array_unique.
Looping over these values using foreach.
Getting the key-value pairs intersecting with the current value using array_intersect.
Code:
# Iterate over every value and intersect it with the original array.
foreach(array_unique($arrayAll) as $v) ${"array$v"} = array_intersect($arrayAll, [$v]);
Advantage:
The advantage of this answer when compared to other given answers is the fact that it uses array_unique to find the unique values and therefore iterates only twice instead of n times.
Check out a live demo here.
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
)
Is it possible to define an array where I can access the elements via their string and numeric index?
array_values() will return all values in an array with their indices replaced with numeric ones.
http://php.net/array-values
$x = array(
'a' => 'x',
'b' => 'y'
);
$x2 = array_values($x);
echo $x['a']; // 'x'
echo $x2[0]; // 'x'
The alternative is to build a set of by-reference indices.
function buildReferences(& $array) {
$references = array();
foreach ($array as $key => $value) {
$references[] =& $array[$key];
}
$array = array_merge($references, $array);
}
$array = array(
'x' => 'y',
'z' => 'a'
);
buildReferences($array);
Note that this should only be done if you're not planning on adding or removing indices. You can edit them though.
You can do this.
$arr = array(1 => 'Numerical', 'two' => 'string');
echo $arr[1]; //Numerical
echo $arr['two']; //String
martswite's answer is correct, although if you've already got an associative array it may not solve your problem. The following is an ugly hack to work around this - and should be avoided at all cost:
$a = array(
'first' => 1,
'second' => 2,
'third' => 3
);
$b=array_values($a);
print $b[2];
PHP allows a mixture of string and numeric-indexed elements.
$array = array(0=>'hello','abc'=>'world');
echo $array[0]; // returns 'hello'
echo $array['0']; // returns 'hello'
echo $array['abc']; // returns 'world';
echo $array[1]; // triggers a PHP notice: undefined offset
A closer look at the last item $array[1] reveals that it is not equivalent to the 2nd element of the array.