Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.