0

Currently I have an array sort. Sort has only one key / value. The keys and values are always different. This array always has just 1 key/value pair. How do I access both elements dynamically in laravel?

I have already solved this but think it is extremely inefficient.

my current solution

I made a function orderQuery() to return the key name.

function orderQuery() {
    foreach (Input::get('sort') as $key => $value) {
        return $key; // there is only 1 item in the array but this looks like bad practice
    }
}

Then I call it like this to respond to my request

->orderBy(orderQuery(), Input::get('sort.'.orderQuery()))

Is there a better way to do this?

1 Answer 1

1

You can use key()

$key = key(Input::get('sort'));

If you want to be save reset the pointer first:

$sort = Input::get('sort');
reset($sort);
$key = key($sort);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this seems much cleaner and better practice. I am using $value = Input::get("sort.$key"); to get the value from key now. :)

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.