0

I've got some PHP which I'm sure could be done a little more elegantly. It functionally works, so it's more just for self learning.

I have an array (or object) with different alphabetic keys, and I'm looking to find out if a key is set, and if so, to return the remaining match.

The PHP code I have at the moment is just a basic if statement:

if(isset($item->revision->application_uid)) $item->type = 'application';
elseif(isset($item->revision->channel_uid)) $item->type = 'channel';
elseif(isset($item->revision->workout_uid)) $item->type = 'workout';

So essentially, I'm wanting to search all of the keys, and return the remaining part of the '_uid' key.

[EDIT] Further to this, I've come up with an alternative suggestion, however I'm still wondering if there's a better/more efficient way to do this.

foreach(array_keys((array) $item->revision) as $key)
{
    if($match = strstr($key, '_uid', TRUE))
    {
        $item->type = $match;
        break;
    }
}

Thanks in advance.

0

1 Answer 1

1

Your code is a bit duplicated, foreach provides the keys already, so you don't need to call array_keys:

foreach ($item->revision as $key => $value)
{
    if ($match = strstr($key, '_uid', TRUE))
    {
        $item->type = $match;
        break;
    }
}

So this does not look that bad. Perhaps you want to initialize with a NULL value or some default value in case no type can be found:

$item->type = 'none';

foreach ($item->revision as $key => $value)
{
    if ($match = strstr($key, '_uid', TRUE))
    {
        $item->type = $match;
        break;
    }
}

Then wrap this into a function of it's own:

function findUidKey($item) {

    foreach ($item->revision as $key => $value)
    {
        if ($match = strstr($key, '_uid', TRUE))
        {
            return $match;
        }
    }

    return 'none';        
}

And call that function instead:

$item->type = findUidKey($item);

Further on you can wrap this even inside another class, but perhaps leave that for another time, just start to stick to functions.

Sign up to request clarification or add additional context in comments.

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.