Thursday, 30 August 2018

Pass the PHP associative array cursor as a function parameter

I'm trying to figure out how to pass an array cursor (i.e. an arbitrary location in an array) as a function parameter. Assume I've got the following array:

$recipe = array("ingredient1"=>array(
                    "type"=>"cheddar cheese",
                    "quantity"=>"1 cup",
                    "format"=>"shredded"
                ),
                "ingredient2"=>array(
                     "type"=>"wheat bread",
                      "quantity"=>"2 slices"
                 )
          );

Assume additionally that I've got a function thingee(&$recipe) that (obviously) accepts $recipe as a parameter by reference.
Question: How can I pass thingee() a location within $recipe, i.e. $recipe["ingredient1"]["quantity"]$recipe["ingredient2"]["type"], etc.

You can just pass it as you indicate:
function thingee(&$recipe) {
    $recipe = "gouda";
}

$recipe = array("ingredient1"=>array("type"=>"cheddar cheese"));
thingee($recipe["ingredient1"]["type"]);
echo $recipe["ingredient1"]["type"]; // outputs: gouda

However, you cannot expect in the function thingee to be able to move to another element in the global $recipe array. It just receives that one element without "parent" or "sybling" context.

0 comments:

Post a Comment