1

When using a foreach loop it works with no issues, but I don't know how to implement this inside a function.

The function I'm trying to write.

function fgf($array, $section_k, $section_n) {
    foreach($array as &$k_687d) {
        $k_687d['section']      = section_k;
        $k_687d['section_name'] = $section_n;
        $k_687d['section_ssn']  = 'df6s';
    }
    return $array;
}

The Array Example.

$array = array(
    'work'=>array(
        'default'  => 1, 
        'opt_type' => 'input',
    ),
    'something_else' => array(
        'default'  => 1, 
        'opt_type' => 'list',
    ),
)

CALL

fgf($array, 'work_stuff', 'Work Stuff');

3 Answers 3

1

I think you intended something like

function fgf($array, $section_k, $section_n)
{
    $newArray = [];            

    for($i = 0, $count = count($array); $i <= $count; $i++) {
        $newArray[$i]['section']      = $section_k;
        $newArray[$i]['section_name'] = $section_n;
        $newArray[$i]['section_ssn']  = 'df6s';
    }

    return $newArray;
}

Then you may call it assigning the resulting array to a variable

$newArray = fgf($array, 'work_stuff', 'Work Stuff');
Sign up to request clarification or add additional context in comments.

1 Comment

Ok, the problem was I wasn't assigning the old array variable with the new array. If you can edit your answer and put the original contents of the function on the question.
0

You're not using your return value, so your $array variable stays unaltered.

You should either assign the return value of your function to the variable, eg.:

$array = fgf($array, 'work_stuff', 'Work Stuff');

or use "Pass by reference":

function fgf(&$array, $section_k, $section_n)

(notice the ampersand before the $array argument). In this case you can remove the return-statement from your function. See: http://php.net/manual/en/language.references.pass.php

Comments

0

You have missed $:

$k_687d['section']      = $section_k;
                          ^

And if you want the original array to be modified, pass the array as reference otherwise assign your calling function to a variable.

Comments

Your Answer

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.