2
\$\begingroup\$

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?

asked Oct 9, 2013 at 16:23
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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.

answered Oct 10, 2013 at 9:57
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.