NotionCommotion Posted October 13, 2018 Share Posted October 13, 2018 Given ['someGroup', 'someSubgroup', 'someProperty'], how can I tell if $array['someGroup']['someSubgroup']['someProperty'] is set and if so return the value? Use case: The following method receives argument such as someProperty, someGroup.someProperty, someGroup.someSubgroup.someProperty, etc which are period delimited, and checks if the value is set and if so returns the value. I am looking at a more generic approach which is not hard coded to three levels. As I write this, I see I can use some loop, but still question whether there is a more elegant approach public function get(string $property) { $arr=explode('.',$properties); switch(count($arr)) { case 1: if(isset($this->properties[$arr[0]])) { return $this->properties[$arr[0]]; } else { throw new AccountException("Property '$property' does not exist."); } break; case 2: if(isset($this->properties[$arr[0]][$arr[1]])) { return $this->properties[$arr[0]][$arr[1]]; } else { throw new AccountException("Property '$property' does not exist."); } break; case 3: if(isset($this->properties[$arr[0]][$arr[1]][$arr[2]])) { return $this->properties[$arr[0]][$arr[1]][$arr[2]]; } else { throw new AccountException("Property '$property' does not exist."); } break; default: throw new AccountException("Invalid property '$property'. Only 3 levels are supported"); } } Quote Link to comment Share on other sites More sharing options...
kicken Posted October 13, 2018 Share Posted October 13, 2018 Loop over the keys you want to check. If the key exists in the array, set the array to it's value and check the next key. Otherwise return null (or whatever). function getValue($array, $keySpec){ foreach (explode('.', $keySpec) as $key){ if (!isset($array[$key])){ return null; } $array = $array[$key]; } return $array; } $array = [ 'userList' => [ '1234' => [ 'name' => 'Kicken' ] ] ]; var_dump(getValue($array, 'userList.1234.name')); https://3v4l.org/AdcKW Quote Link to comment Share on other sites More sharing options...
NotionCommotion Posted October 13, 2018 Author Share Posted October 13, 2018 Thanks kicken, I ended up using the following, but will try your solution out as well. public function get(string $property) { $keys=explode('.',$property); $properties = $this->read(false); while($key = array_shift($keys)){ if(isset($properties[$key])) { $properties = $properties[$key]; } else { break; } } if(!is_array($properties)) { return $properties; } else { throw new AccountException("Property '$property' does not exist."); } } Quote Link to comment Share on other sites More sharing options...
requinix Posted October 13, 2018 Share Posted October 13, 2018 Same difference. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.