Accessing array elements using the associative index and numbered index - php

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.

Related

Is there a built-in way to retrieve a PHP array element such that it is removed from the array?

Is there a built-in way to retrieve a PHP array element such that it is removed from the array? Similar to array_pop(), but on a specific index? For example:
<?php
$array = [
'foo' => 123,
'bar' => 456,
'baz' => 789
];
$bar = array_get_and_remove($array, 'bar');
/* Outputs:
* $bar = 456,
* $array = ['foo' => 123, 'baz' => 789]
*/
$element = $array[$key];
unset($array[$key]);
So to make your function (be sure to use a reference &):
function array_get_and_remove(&$array, $key);
$element = $array[$key];
unset($array[$key]);
return $element;
}
Then:
$bar = array_get_and_remove($array, 'bar');
There is no one function built-in way. Aammad Ullah got right to it while I overthunk it, but here's a simple way. $result will contain 'bar' => 456 and it will be removed from $array:
$array = array_diff_key($array, $result = ['bar' => $array['bar']]);
Assign 'bar' => $array['bar'] array to $result
Compute difference of array and $result
Using array_splice():
$result = array_splice($array, array_search('bar', array_keys($array), true), 1);
Get an array of the string keys array_keys()
Search that array for bar returning the numeric key/offset array_search()
Use that offset and length of 1 to remove that element and return it array_splice()
To get just the value use something like current():
$result = current(array_splice($array, array_search('bar', array_keys($array), true), 1));

How can i convert ARRAY into VARIABLE? [duplicate]

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

PHP Dynamically accessing an associative array

EDITED FROM ORIGINAL THAT HAD IMPLIED ONLY 1 ACCESS
If I have an array that contains x number of arrays, each of the form
array('country' => array('city' => array('postcode' => value)))
and another array that might be
array('country', 'city', 'postcode') or array('country', 'city')
depending on what I need to retrieve, how do I use the second array to identify the index levels into the first array and then access it.
By nesting references with $cur = &$cur[$v]; you can read and modify the original value:
Live example on ide1: http://ideone.com/xtmrr8
$array = array('x' => array('y' => array('z' => 20)));
$keys = array('x', 'y', 'z');
// Start nesting new keys
$cur = &$array;
foreach($keys as $v){
$cur = &$cur[$v];
}
echo $cur; // prints 20
$cur = 30; // modify $array['x']['y']['z']
Loop through the array of indexes, traveling down the initial array step by step until you reach the end of the index array.
$array1 = array('x' => array('y' => array('z' => 20)));
$keys = array('x', 'y', 'z');
$array_data = &$array1;
foreach($keys as $key){
$array_data = &$array_data[$key];
}
echo $array_data;
Ok, I apologize for not having expressed my question more clearly, originally, but I got it to work as I was hoping, with a variable variable, as follows:
$keystring = '';
foreach ($keys as $key) {
$keystring .= "['$key']";
}
Then iterate the main array, for each of the country entries in it, and access the desired value as:
eval('$value = $entry' . "$keystring;");

PHP - Get key name of array value

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

Best way to test if array key exists

Imagine that I want to create an array from another array like this:
$array = array('bla' => $array2['bla'],
'bla2' => $array2['bla2'],
'foo' => $array2['foo'],
'Alternative Bar' => $array['bar'],
'bar' => $array2['bar']);
What is the best way to test either the $array2 has that index I'm passing to the other array, without using an if for each index I want to add.
Note that the key from the $array can be different from the $array2
What I did was, creating a template to the array with the keys that I want e.g.
$template = array('key1', 'key2', 'key3');
Then, I would merge the template with the other array, if any key was missing in the second array, then the value of the key would be null, this way I don't have the problem of warnings telling me about offset values.
$template = array('key1', 'key2', 'key3');
$array = array_merge($template, $otherarray);
if i understood right...
$a = array('foo' => 1, 'bar' => 2, 'baz' => 3);
$keys = array('foo', 'baz', 'quux');
$result = array_intersect_key($a, array_flip($keys));
this will pick only existing keys from $a
A possibility would be:
$array = array(
'bla' => (isset($array2['bla']) ? $array2['bla'] : ''),
'bla2' => (isset($array2['bla2']) ? $array2['bla2'] : ''),
'foo' => (isset($array2['foo']) ? $array2['foo'] : ''),
'xxx' => (isset($array2['yyy']) ? $array2['yyy'] : ''),
'bar' => (isset($array2['bar']) ? $array2['bar'] : '')
);
If this shoud happen more dynamically, I would suggest to use array_intersect_key, like soulmerge posted. But that approach would have the tradeoff that only arrays with the same keys can be used.
Since your keys in the 2 arrays can vary, you could build something half-dynamic using a mapping array to map the keys between the arrays. You have at least to list the keys that are different in your arrays.
//key = key in $a, value = key in $b
$map = array(
'fooBar' => 'bar'
);
$a = array(
'fooBar' => 0,
'bla' => 0,
'xyz' => 0
);
$b = array(
'bla' => 123,
'bar' => 321,
'xyz' => 'somevalue'
);
foreach($a as $k => $v) {
if(isset($map[$k]) && isset($b[$map[$k]])) {
$a[$k] = $b[$map[$k]];
} elseif(isset($b[$k])){
$a[$k] = $b[$k];
}
}
That way you have to only define the different keys in $map.
You want to extract certain keys from array1 and set non-existing keys to the empty string, if I understood you right. Do it this way:
# Added lots of newlines to improve readability
$array2 = array_intersect_key(
array(
'bla' => '',
'bla2' => '',
'foo' => '',
# ...
),
$array1
);
Perhaps this...
$array = array();
foreach ( $array2 as $key=>$val )
{
switch ( $key )
{
case 'bar':
$array['Alternative bar'] = $val;
break;
default:
$array[$key] = $val;
break;
}
}
For any of the "special" array indexes, use a case clause, otherwise just copy the value.

Categories