Add elements to an array inside a foreach loop I have the code below:

&lt;?php

$i = array(1, 2, 3);

$w = array(1 =&gt; '11', 2 =&gt; '22', 3 =&gt; '33');

foreach ($i as $f) {
    $ws = $w[$f];

    $file_names[] = array(
        'fn' =&gt; 'fname',
        'sn' =&gt; 'sname',
        'is' =&gt; 'is',
        'rv' =&gt; 'rv'
    );

    foreach ($file_names as $k =&gt; $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'  =&gt; '3',
                'min'   =&gt; 'min',
                'max'   =&gt; 'max',
                'value' =&gt; "" . $ws . ""
            );
        }
    }
}

print_r($file_names);

?&gt;


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 =&gt; $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'  =&gt; '3',
                'min'   =&gt; 'min',
                'max'   =&gt; 'max',
                'value' =&gt; "" . $ws . ""
            );
        }
    }


Is there any way to write this in a more elegant manner?
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' =&gt; "" . $ws . ""  , you could just look up the value of $ws in the particular array rather than iterating the entire array every time.