I have the code below:
<?php
$i = array(1, 2, 3);
$w = array(1 => '11', 2 => '22', 3 => '33');
foreach ($i as $f) {
$ws = $w[$f];
$file_names[] = array(
'fn' => 'fname',
'sn' => 'sname',
'is' => 'is',
'rv' => 'rv'
);
foreach ($file_names as $k => $v) {
if (!isset($file_names[$k]['mod'])) {
$file_names[$k]['mod'] = array(
'ct',
'pt'
);
}
if (!isset($file_names[$k]['pw'])) {
$file_names[$k]['pw'] = array(
'task' => '3',
'min' => 'min',
'max' => 'max',
'value' => "" . $ws . ""
);
}
}
}
print_r($file_names);
?>
What I’m trying to do is add new elements to an array in some particular conditions. The only thing that I don’t like is the second foreach
loop part. I.e.:
foreach ($file_names as $k => $v) {
if (!isset($file_names[$k]['mod'])) {
$file_names[$k]['mod'] = array(
'ct',
'pt'
);
}
if (!isset($file_names[$k]['pw'])) {
$file_names[$k]['pw'] = array(
'task' => '3',
'min' => 'min',
'max' => 'max',
'value' => "" . $ws . ""
);
}
}
Is there any way to write this in a more elegant manner?
1 Answer 1
maybe I am missing something, but why do you even need to have two different arrays $i and $w? second thing, $file_names
array should go outside of the foreach loop since this array doesn't depend on the iteration of the first foreach loop.
I am not sure about the exact output which you expect but it seems that you can only iterate through the file names array and when you need to update this line
'value' => "" . $ws . ""
, you could just look up the value of $ws in the particular array rather than iterating the entire array every time.