Change value in multidimension associative array PHP - php

I must be missing something about how PHP arrays are handled. When I execute the following code:
<?php
$ary = array(
"alpha" => array("A"=>1,"B"=>2,"C"=>3),
"beta" => array("A"=>7,"B"=>8,"C"=>9)
);
foreach ($ary as $key => $vals) {
$vals["B"]=99;
echo $key."= ".$vals["A"]." ".$vals["B"]." ".$vals["C"]."<br>";
}
echo $ary['alpha']["B"]."<br>";
?>
I get:
alpha= 1 99 3
beta= 7 99 9
2
The change to 99 in each case seems to be lost. What am I doing wrong?

If you want to change items of array in foreach statement you should pass by reference.
foreach ($ary as $key => &$vals) {
}

<?php
$ary = array(
"alpha" => array("A"=>1,"B"=>2,"C"=>3),
"beta" => array("A"=>7,"B"=>8,"C"=>9)
);
foreach ($ary as $key => $vals) {
//$vals["B"]= 99;
$ary[$key]["B"] = 99;
echo $key."= ".$vals["A"]." ".$vals["B"]." ".$vals["C"]."<br>";
}
echo $ary['alpha']["B"]."<br>";
?>

Related

Get foreach numeric index when keys are named

This question is just for fun and out of curiosity.
Edit : My question is different than
How to find the foreach index
Because $key has already a non-numeric value in my case.
Without having a variable outside a foreach that is increment inside the foreach scope, as the usual $i, is there a way to get the index of an item when $key is already named ?
Exemples :
$myNumericIndexArray = ('foo', 'bar', 'go', 'habs');
foreach($myNumericIndexArray as $key => $value){
//Here $key will be 0 -> 1 -> 2 -> 3
}
Now, if I have :
$myNamedIndexArray = ('foo' => 'bar', 'go' => 'habs', 'CSGO_bestTeam' => 'fnatic');
foreach($myNamedIndexArray as $key => $value){
//Here $key will be foo -> go -> CSGO_bestTeam
}
Can I, without having to :
$i=0;
foreach($myNamedIndexArray as $key => $value){
//Here $key will be foo -> go -> CSGO_bestTeam
$i++;
}
access the index of a named array. Something declared in the foreach declaration like in a for or a status of $key ?
Have a good one.
If you really want index array of associative array than try this:
$myNamedIndexArray = ['foo' => 'bar', 'go' => 'habs', 'CSGO_bestTeam' => 'fnatic'];
$keys = array_keys($myNamedIndexArray);
foreach($myNamedIndexArray as $key => $value){
echo array_search($key, $keys);
}
I don't know why you would want to do an array_keys() and array_search() every loop iteration. Just build a reference array and you can still foreach() the original:
$positions = array_flip(array_keys($myNamedIndexArray));
foreach($myNamedIndexArray as $key => $value){
echo "{$key} => {$value} is position {$positions[$key]}\n";
}
Something like this :
<?php
$myNamedIndexArray = array('foo' => 'bar', 'go' => 'habs', 'CSGO_bestTeam' => 'fnatic');
$numericIndexArray = array_keys($myNamedIndexArray);
foreach($numericIndexArray as $key=>$value){
echo $key.'</br>'; //here key will be 0 1 2
echo $value. '</br>';
}
I'd try something like this:
<?php
$myNamedIndexedArray = ['foo' => 'bar', 'go' => 'habs', 'CSGO_bestTeam' => 'fnatic'];
$myNumberIndexedArray = array_keys($myNamedIndexedArray);
foreach($myNumberIndexedArray as $key => $value){
echo $key. " => " . $myNamedIndexedArray[$myNumberIndexedArray[$key]]."<br />";
}
?>
Adn the output will be:
0 => bar
1 => habs
2 => fnatic

echo array inside array in order

I have this some arrays that look like this,
$array = Array(
'Homer' => Array
(
'id' => 222,
'size' => 12
),
'Bart' => Array
(
'id' => 333,
'size' => 3
)
);
I would like to echo Homer: id is 222, size is 12
then in the next line echo Bart: id is 333, size is 3 using a foreach loop as key and values.
So i basically want to echo all the Simpsons character names which have their id and size next their names.
I tired this but it printed homer too many times and it even used Bart's id and size at one point.
foreach( $array as $billdate => $date) {
foreach( $date as $k => $v) {
echo $billdate; // Prints Homer and bart
foreach($array as $innerArray){
foreach($innerArray as $key => $value){
echo "[". $key ."][". $value ."] <br/>";
}}
}
}
Thanks in advance.
you can try like this:
foreach( $array as $billdate => $date) {
echo $billdate.': id is '.$date['id'].', size is '.$date['size'];
}
Don't use so many foreach ,just think your need loop ...
foreach( $array as $billdate => $date) {
echo $billdate; // Prints Homer and bart
foreach($date as $key => $value){
echo "[". $key ."][". $value ."] <br/>";
}
}

Array ksort only shows non-like values?

Have an array for a ranking script.
Some times the key will be the same. They are numeric.
When the sort is ran, only non-like values are echoed.
Can't figure out the fix.
$list = array( $value1 => 'text', $value2 => 'text', $value3 => 'text');
krsort($list);
foreach ($list as $key => $frame) {
echo $frame;
}
If you assign two values to the same key in an array, the first value will be overridden by the second. You'll therefore end up with only one value for that key in the array.
To resolve this, I'd suggest to change your array structure like this:
<?php
$list = array( $key1 => array($key1member1, $key2member2),
$key2 => array($key2member1),
$key3 => array($key3member1, $key3member2, $key3member3) );
krsort($list);
foreach ($list as $key => $frames) {
foreach ($frames => $frame) {
echo $frame;
}
}
?>
Going by what you wrote in the comments to this question and my other answer, I'd recommend to switch keys and values.
<?php
$list = array( "frame1" => 4, "frame2" => 2, "frame3" => 99, "frame4" => 42 );
arsort($list);
foreach ($list as $frame => $ranking) {
echo $frame;
}
?>

How to use foreach to verify value in a 3-dimensional array without having duplicated output in php?

Hi my question is a little tricky, I got a 3-dimensional array and try to verify the 3rd level value and echo both 1st and 3rd level values.
The following is the code example, and my failed approaches.
$myArray=array(
"mySub0" => arrary(
0 => array("mySubSub0" => "1","mySubSub1" => "a"),
1 => array("mySubSub0" => "2","mySubSub1" => "b"),
2 => array("mySubSub0" => "3","mySubSub1" => "b"),
),
"mySub1" => arrary(
0 => array("mySubSub0" => "4","mySubSub1" => "a"),
1 => array("mySubSub0" => "5","mySubSub1" => "a"),
2 => array("mySubSub0" => "6","mySubSub1" => "a"),
),
"mySub2" => arrary(
0 => array("mySubSub0" => "7","mySubSub1" => "a"),
1 => array("mySubSub0" => "8","mySubSub1" => "b"),
2 => array("mySubSub0" => "9","mySubSub1" => "a"),
),
),
I want to check if the value of "mySubSub1" is b. if yes, echo the value of "mySubSub0" and the related key in first-level of the array. It should be like this:
mySub0
2
3
mySub2
8
My failed approach is
foreach ($myArray as $a => $b)
{
foreach ($b as $c)
if($c[mySubSub1]=="b")
{
echo $a
echo $c[mySubSub0];
}
else {
}
}
The result will have one duplicate mySub0
mySub0
2
mySub0
3
mySub2
8
if I move the "echo $a" out of the "if"
foreach ($myArray as $a => $b)
{
echo $a
foreach ($b as $c)
if($c[mySubSub1]=="b")
{
echo $c[mySubSub0];
}
else {
}
}
the result would be
mySub0
2
3
mySub1
mySub2
8
one unwanted "mySub1" because there is no place to verify if there is a value b.
It has bothered my a lot today. I tried to Google but haven't found the right answer.
Really hope someone can help me. Thank you in advance
Here's something that should work:
function find_value($arr, $key, $value, $sibling)
{
foreach ($arr as $k => $v)
{
$results = _find_value($v, $key, $value, $sibling);
if (count($results) > 0) {
echo $k;
foreach ($results as $result) {
echo $result;
}
}
}
}
function _find_value($arr, $key, $value, $sibling)
{
$out = array();
foreach ($arr as $k => $v)
{
if ($v[$key] == $value)
$out[] = $v[$sibling];
}
return $out;
}
find_value($myArray, "mySubSub1", "b", "mySubSub0");
Basically, the main function loops over items in the outer array, calling the inner function to get a list of the "sibling" keys where the main key matches the value you're looking for. If a non-zero number of results are obtained in the inner function, echo and loop.
Hopefully this does the trick for you.

Retrieve array key passed on value PHP

I have the following array
$group= array(
[0] => 'apple',
[1] => 'orange',
[2] => 'gorilla'
);
I run the array group through an for each function and when the loop hits values of gorilla I want it to spit out the index of gorilla
foreach ($group as $key) {
if ($key == gorilla){
echo //<------ the index of gorilla
}
}
You can use array_search function to get the key for specified value:
$key = array_search('gorilla', $group);
foreach( $group as $index => $value) {
if ($value == "gorilla")
{
echo "The index is: $index";
}
}
array_search — Searches the array for a given value and returns the corresponding key if successful
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>
foreach($group as $key => $value) {
if ($value=='gorilla') {
echo $key;
}
}
The foreach($c as $k => $v) syntax is similar to the foreach($c as $v) syntax, but it puts the corresponding keys/indices in $k (or whatever variable is placed there) for each value $v in the collection.
However, if you're just looking for the index of a single value, array_search() may be simpler. If you're looking for indices for many values, stick with the foreach.
Try this:
foreach ($group as $key => $value)
{
echo "$key points to $value";
}
foreach documentation on php.net

Categories