Forum Moderators: coopster

Message Too Old, No Replies

Associative array when one key doesn't have a value

         

csdude55

7:07 pm on Oct 1, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I'm working with something like this:

$arr = [
'lorem' => 'one',
'ipsum' => 'two',
'foo'
]

foreach ($arr as $key => $val)
echo "$key => $val\n";

// Result:
// lorem => one
// ipsum => two
// 0 => foo


"foo" is the one throwing me off, for whatever reason it seems to start over as a numeric index when I expected it to be foo => false.

Assuming that I can't change the $arr variable, can you suggest a way to modify the loop so that "foo" is a key?

vincevincevince

7:15 pm on Nov 2, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You'll need to check and re-write it into a new array, probably line by line.

$arr=fixit($arr);
function fixit($arr)
{
foreach ($arr as $k=>v) {
if (is_int($k)) $newarr[$v]=false;
else $newarr[$k]=$v;
}
return $newarr;
}

robzilla

10:58 pm on Nov 2, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Alternatively:
$arr = [
'lorem' => 'one',
'ipsum' => 'two',
'foo'
];


foreach ($arr as $key => $val) {
if(is_int($key)) {
unset($arr[$key]);
$key = $val;
$arr[$key] = $val = false;
}
echo "$key => $val\n";
}
print_r($arr);

Returns:
lorem => one
ipsum => two
foo =>

Array
(
[lorem] => one
[ipsum] => two
[foo] =>
)

Or you can leave $arr unchanged, of course, and just do:
foreach ($arr as $key => $val) {
if(is_int($key)) { $key = $val; $val = false; }
echo "$key => $val\n";
}

This is all assuming you're sure you won't have any valid key value pairs where the key is an integer.