Question

I created a script with two variables $state and $sectors. I want to display the sector if the state is in that sector. The example below uses 'Arizona' as the state and it should output the sector as 'southwest' but I do not think I am working with the array properly:

    <?php

    $state = 'Arizona';

    $sectors = array(
                "Southeast" => array(
                        'name' => 'Southeast',
                        'states'    => array('Alabama', 'Georgia', 'Florida', 'South Carolina', 'North Carolina', 'Louisiana', 'Tennessee', 'Kentucky', 'West Virginia', 'Mississippi')
                ),
                    "Southwest" => array(
                            'name' => 'Southwest',
                            'states'    => array('California', 'Arizona', 'New Mexico', 'Utah')
                    )
    );

        function has_recursive($sectors, $state)
        {
            foreach ($state as $key => $value) {
                if (!isset($sectors[$key])) {
                    return false;
            }
            if (is_array($sectors[$key]) && false === has_recursive($sectors[$key], $value)) {
                return false;
            }
        }
        return true;
    }

    if (has_recursive($sectors, $state) == true){
     // false or true
        echo $sector['name'];  // Displays Southwest
    }

Please help.

Was it helpful?

Solution

Try this:

function get_sector($sector_array, $state_name) {

    foreach ($sector_array as $sec) 
        if (in_array($state_name, $sec))
            return $sec['name'];

    return false;
}

Given $state and $sectors as defined in your question...

echo get_sector($sectors, $state); // prints "Southwest"

UPDATE regarding comment:

There are several different approaches to the "not found" return value. What works best for your application is up to you, but here are a few examples:

return false;

//This would be used like this:
if (!$sect = get_sector($sectors, $state))
    echo "A custom error message"
else
    echo "Sector = " . $sect;

OR you could return a specific string:

return "Sector not found."; 
// Return a standard error message

OR a customized string:

return "No sector match for the state of " . $state_name; 
// Return a specific error message

OTHER TIPS

This function should work.

function getSector($stateName, $sectorList) {
   foreach($sectorList as $sector) {
      if( in_array($stateName, $sector['states'] ) {
         return $sector['name'];   
      }
   }
 // If state is not found
 return 'NOT FOUND';
}

Example of use in your code is:

echo getSector($state, $sectors);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top