Ibn Saeed
Ibn Saeed

Reputation: 3301

Can you describe the following PHP function?

Can anyone describe the following php function:

function get_setting_value($settings_array, $setting_name, $default_value = "")
    {
        return (is_array($settings_array) && isset($settings_array[$setting_name]) && strlen($settings_array[$setting_name])) ? $settings_array[$setting_name] : $default_value;
    }

What does it return and whats its purpose?

Upvotes: 0

Views: 210

Answers (3)

Shadi Almosri
Shadi Almosri

Reputation: 11989

if $settings_array is an array and the setting $setting_name (which is fournd in the settings array) has a value and the value of $setting_array[$setting_name] has a value, then return the value of $setting_array[$setting_name] otherwise return the $default value.

I guess the purpose of this is go get a particular setting and check that it exists (the settings are all in the array, they are set and the have a length) if not then return your default values.

This uses an "inline if statement"

Upvotes: 1

Mercer Traieste
Mercer Traieste

Reputation: 4678

The function returns a setting value if found, or the default value (which is optional).

A more detailed answer:

  • if the the given settings array is an actual array
  • if the setting_name exists in the array
  • if the setting value represented by the setting name is not empty, false, or 0 then return it
  • else return the default value, which, if not set, is an empty string

Upvotes: 3

Emil H
Emil H

Reputation: 40240

This is equivalent:

function get_setting_value($settings_array, $setting_name, $default_value = "")
{
    // Check that settings array really is an array
    if (!is_array($settings_array)) {
        return $default_value;
    }
    // Check that the array contains the key $setting_name
    if (!isset($settings_array[$setting_name])) {
        return $default_value;
    }
    // Check that the value of that index isn't an empty string
    if (!strlen($settings_array[$setting_name])) {
        return $default_value;
    }

    // Return the requested value
    return $settings_array[$setting_name];
}

Upvotes: 5

Related Questions