2

I don't have much PHP experience and I want to know how to best create a recursive function in PHP. Take this example

$config = array(
    "MYSQL" => array(
        "SERVER" => "localhost",
        "USERNAME" => "root",
        "PASSWORD" => ""
    ),
    "FOO" => "bar"
);

// Make the config global
config_parse(false, $config);

function config_parse($index, $value)
{
    if(is_array($value))
    {
        foreach($value as $i => $e)
        {
            config_parse(($index ? $index . "_" : "") . $i, $e);
        }
    }
    else
    {
        define($index, $value);
    }
}

It does what I want it to do, but I feel that I'm "hacking"/writing bad code when I initialize the recursive function in this way (passing false as the initial index and checking for it in the function)

A way to work around this could be to reverse the order of the input parameters, which means that the index value wouldn't be accessed when an array was passed as value.

Another way could be to split the recursive function into initiation function and callback function.

What I want to know is what's the "best practice", preferably based on my example.

Thanks for replies

2 Answers 2

3

For me it depends on the complexity of the recursion. In the specific example you give i would just flip the parameters and make the second default to null (i prefer null over false in this case).

function config_parse($value, $index = null)
{
  // your logic - id detect null with if(null === $index)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah optional parameters at the end with default values for the non-recursive case. The caller shouldn't even need to know about them—other than not to provide values.
0

This may not be feasible if you have an existing system, however I would argue that you probably do want a common prefix to a set of loaded configs in general so that different configs don't unintentionally clobber each other. This also makes the code shorter and cleaner:

function parseConfig($config,$index='CONFIG'){
  if(is_array($config)){
      foreach($config as $suffix => $subConfig){
          parseConfig($index . '_' . $suffix, $subConfig)
   }else{
       define($index,$config)
   }
}

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.