Relm
Relm

Reputation: 8272

Push value to multidimensional array within a foreach loop, inside a custom function

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');

Upvotes: 1

Views: 123

Answers (3)

Thamilhan
Thamilhan

Reputation: 13313

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.

Upvotes: 0

phaberest
phaberest

Reputation: 3220

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');

Upvotes: 1

bartvanraaij
bartvanraaij

Reputation: 343

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

Upvotes: 0

Related Questions