Forum Moderators: coopster

Message Too Old, No Replies

Overwriting value of multidimensional array

         

csdude55

10:23 pm on Sep 22, 2023 (gmt 0)

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



I currently have something like this:

$name = $_GET['name']; // user inputs "WebmasterWorld", for example

$arr = [
'csdude' = [
'lorem' => 14,
'ipsum' => 427,
'this' => 49,
'that' => 62,
'whatever' => 27
],

'WebmasterWorld' = [
'lorem' => 211,
'ipsum' => 38,
'this' => 119,
'that' => 30,
'whatever' => 318
]
];

if (isset($foo)) {
$arr['csdude']['this'] = 50;
$arr['csdude']['whatever'] = 729;

$arr['WebmasterWorld']['this'] = 207;
$arr['WebmasterWorld']['whatever'] = 6;
}


That if (isset($foo)) { ... } condition gets complicated and messy when I have 50+ first-dimension values, though. In each case it would change the value of the "this" and "whatever".

I started going down this alternative path, but I don't know that it's actually any easier to read or maintain:

$name = 'WebmasterWorld';

$arr = [
'csdude' = [
'lorem' => 14,
'ipsum' => 427,
'this' => 49,
'that' => 62,
'whatever' => 27
],

'WebmasterWorld' = [
'lorem' => 211,
'ipsum' => 38,
'this' => 119,
'that' => 30,
'whatever' => 318
]
];

$alt= [
'csdude' = [
'this' => 50,
'whatever' => 729
],

'WebmasterWorld' = [
'this' => 207,
'whatever' => 6
]
];

if (isset($foo))
foreach (['this', 'whatever'] as $key)
$arr[$name][$key] = $alt[$name][$key];


Can you suggest a third method that would be easier to read and maintain?

Note, it doesn't HAVE to be a multidimensional array. At the end, I just need variables that look like this:

$name = 'WebmasterWorld';

foreach ($arr[$name] as $k => $v)
$$k = 'this, ' . $v . ', that';

echo <<<EOF
$lorem
$ipsum
$this
$that
$whatever
EOF;