PHP Dynamically accessing an associative array - php

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;");

Related

PHP Array split string and Integers

Below is an array of strings and numbers. How could the string and number values be split into separate arrays (with strings in one array and numbers in another array)?
array('a','b','c',1,2,3,4,5,'t','x','w')
You could also do this in one line using array_filter()
$numbers = array_filter($arr,function($e){return is_numeric($e);});
$alphas = array_filter($arr,function($e){return !is_numeric($e);});
print_r($numbers);
print_r($alphas);
Loop through them, check if is_numeric and add to appropriate array:
$original = array('a','b','c',1,2,3,4,5,'t','x','w');
$letters = array();
$numbers = array();
foreach($original as $element){
if(is_numeric($element)){
$numbers[] = $element;
}else{
$letters[] = $element;
}
}
https://3v4l.org/CAvVp
Using a foreach() like in #jnko's answer will be most performant because it only iterates over the array one time.
However, if you are not concerned with micro-optimization and prefer to write concise or functional-style code, then I recommend using array_filter() with is_numeric() calls, then making key comparisons between the first result and the original array.
Code: (Demo)
$array = ['a','b',0,'c',1,2,'ee',3,4,5,'t','x','w'];
$numbers = array_filter($array, 'is_numeric');
var_export($numbers);
var_export(array_diff_key($array, $numbers));
Output:
array (
2 => 0,
4 => 1,
5 => 2,
7 => 3,
8 => 4,
9 => 5,
)
array (
0 => 'a',
1 => 'b',
3 => 'c',
6 => 'ee',
10 => 't',
11 => 'x',
12 => 'w',
)
$data = array('a','b','c',1,2,3,4,5,'t','x','w');
$integerArray = array();
$stringArray = array();
$undefinedArray = array();
foreach($data as $temp)
{
if(gettype($temp) == "integer")
{
array_push($integerArray,$temp);
}elseif(gettype($temp) == "string"){
array_push($stringArray,$temp);
}else{
array_push($undefinedArray,$temp);
}
}

Get the index of the same value of a array php

I have an associative array like this [this array is combination of two different arrays]:
I combine arrays and via array_combine() function
$products = array_combine($one_array_key,$second_array_values);
$products = array(
"arn1" =>"A",
"arn2" =>"A",
"arn3" =>"A",
"arn4" =>"B",
"arn5" =>"B",
"arn6" =>"B"
);
So As you can see there are two distinct values from array A and B.
I want two arrays consists of it's keys.
Or in other words: Compare values of associative array and matched values's key will be extract to the other array .
So My expected out is:
$A = array("arn1","arn2","arn3");
$B = array("arn4","arn5","arn6");
My code:
$products = array_combine($one_array_key,$second_array_values);
$products_distinct_values = array_count_values($product);
$products_distinct_values_keys = array_keys($products_distinct_values);
foreach ($products as $key => $value)
{
// what should I need write there, to get the x numbers of array(s), containing *key* of the same *value of array*
}
I SUPER would never use this "variable variables" technique in a professional project, but it does satisfy your brief. I will urge you to find the folly in your XY Problem.
Effectively, the snippet below will synchronously iterate over the two related input arrays and create variably-named result arrays to push values into.
Code: (Demo)
$one_array_key = ['A', 'A', 'A', 'B', 'B', 'B'];
$second_array_values = ['arn1', 'arn2', 'arn3', 'arn4', 'arn5', 'arn6'];
foreach ($one_array_key as $index => $value) {
$$value[] = $second_array_values[$index];
}
var_export($A);
echo "\n---\n";
var_export($B);
Output:
array (
0 => 'arn1',
1 => 'arn2',
2 => 'arn3',
)
---
array (
0 => 'arn4',
1 => 'arn5',
2 => 'arn6',
)
It makes much more sense to have a statically named variable containing keys and related subarrays. This way you can call array_keys() on the result, if you wish, to find out which groups were found in the original input.
Code: (Demo)
$result = [];
foreach ($one_array_key as $index => $value) {
$result[$value][] = $second_array_values[$index];
}
var_export($result);
Output:
array (
'A' =>
array (
0 => 'arn1',
1 => 'arn2',
2 => 'arn3',
),
'B' =>
array (
0 => 'arn4',
1 => 'arn5',
2 => 'arn6',
),
)
You can use the following PHP code to do that.
<?php
$products = array("arn1"=>"A", "arn2"=>"A", "arn3"=>"A", "arn4"=>"B", "arn5"=>"B", "arn6"=>"B");
$A = array();
$B = array();
foreach ($products as $key => $value)
{
if ($value == "A")
{
array_push ($A, $key);
}
else if ($value == "B")
{
array_push ($B, $key);
}
}
print_r ($A);
print_r ($B);
?>

Independent Nested Loops in PHP

Say i have two different arrays. I want to get each value from the first array, and add to it some values of each key in the second array. How do i do this please?
I tried using a foreach loop inside a foreach loop and for each value in the first array, it appends each value of the second array which isn't what i want
$array1 = array(chris, kate, john, jane);
$array2 = array('first' => 1, 'second' => 2, 'third' => 3, 'fourth' => 4);
foreach($array1 as $name){
foreach($array2 as $k => $v){
echo $name . "-" . $v;
}
}
I want my output to look like this
chris-1
kate-2
john-3
jane-4
Sometimes, the count of both array aren't the same. Some values in the first array produces an empty string, so in cases like that, it should just skip the value. Once the empty string in array1 is skipped or deleted, the count then matches array2
My above nested loop can't give me this. How do i go about this please?
Firstly I would use array_filter() to remove the empty strings from $array1:
$array1 = array(chris, kate, john, jane);
$array1 = array_filter($array1, function($value) {
return $value !== '';
});
Now we need to reindex the array to account for the gaps we made when removing empty strings.
$array1 = array_values($array1);
Considering you don't use the 'first', 'second', etc keys in $array2 for anything, we can just get rid of them using array_values(). This will leave us with an array like array(1,2,3,4) which will make accessing the data later on a little easier.
$array2 = array('first' => 1, 'second' => 2, 'third' => 3, 'fourth' => 4);
$array2 = array_values($array2);
Now we can loop through the first array and access the same position in the second array to create the final string.
// Assign the current element's numeric position to the $i variable on each iteration.
foreach($array1 as $i => $name){
echo $name . "-" . $array2[$i];
}
Final Code
$array1 = ['chris', 'kate', '', 'john', 'jane'];
$array1 = array_filter($array1, function ($value) {
return $value !== '';
});
$array1 = array_values($array1);
$array2 = ['first' => 1, 'second' => 2, 'third' => 3, 'fourth' => 4];
$array2 = array_values($array2);
foreach ($array1 as $i => $name) {
echo $name . "-" . $array2[$i];
}

Get to element in multi-dimensional array using an undetermined number of keys

This is a bit of weird one, but I can't get my head around it. I have a multidimensional array that has an unknown length and unknown number of dimensions. I also have an array of keys like so:
$keys = array(0, 2, 1, 0);
Now, if this array of keys had a determined size I would simply access my multidimensional array like so:
$multidimensional_array[$keys[0]][$keys[1]][$keys[2]][$keys[3]];
The problem is that it doesn't, the length of the keys array will change a lot. Does anyone know of a loop that could iterate across the keys arrays and then access the multidimensional array accordingly?
Assuming such array:
$multidimensional_array = array(
0 => array(
2 => array(
1 => array(
0 => 'value'
)
)
)
);
And these keys:
$keys = array(0, 2, 1, 0);
You can do:
$current = $multidimensional_array;
foreach($keys as $key) {
$current = $current[$key];
}
var_dump($current); //'value'
Edit:
Here's an example with references.
$current = &$multidimensional_array; // <- $current is reference
foreach($keys as $key) {
$current = &$current[$key]; // <- $current is reference again
}
var_dump($current); //'value'
$current = 'otherValue'; // $multidimensional_array[0][2][1][0] value changed to 'otherValue'
unset($current); // remove reference to be sure you won't break something later by an accident
https://3v4l.org/OuAiQ

Accessing array elements using the associative index and numbered index

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.

Categories