0

I have two static hashtables in my program:

public static $labels = [
    'id' => 'ID',
    'name' => 'Name',
    'email' => 'E-mail',
    'password' => 'Password',
];

public static $columnTypes = [
    'id' => 'number',
    'name' => 'text',
    'email' => 'text',
    'password' => 'text',
];

First is for the labels of the database columns and the second for each type (necessary for filtering).

My problem is that I often need to get the type of a column by its label what leads to speed issues (hashtables are pretty slow in this direction right?).

My approaches would be the following:

  1. Type a hashtable label => type which is bad because I have to repeat myself and there is no support for other languages
  2. Create the label => type hashtable in a static content on runtime (is this possible in php?)

Are there better approaches or best practices for this issue and is the second approach possible in php? (maybe with a small example ;)

4
  • 1
    Maybe have a look at array_flip ? Commented Jul 18, 2017 at 8:27
  • I know how to do the flip, but how can I do it in a static content? Commented Jul 18, 2017 at 8:32
  • "hashtables are pretty slow in this direction right?" -- wrong. And, anyway, the only data structure you have in PHP is named "array" but in fact it is a hashtable (aka dictionary, aka association map). Commented Jul 18, 2017 at 8:32
  • Thank you. I thought to get a key of a value you have to iterate over the whole hashtable? Commented Jul 18, 2017 at 8:33

2 Answers 2

3

Call array_flip in the class constructor. To avoid repeating it, check whether the flipped array is already set.

class YourClass {
    public static $labels = [
        'id' => 'ID',
        'name' => 'Name',
        'email' => 'E-mail',
        'password' => 'Password',
    ];
    public static $labels_flipped = null;

    public function __construct() {
        if (!$labels_flipped) {
            $labels_flipped = array_flip($labels);
        }
        ...
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

If you need to get the key having the value then you can use array_search() or array_keys().

If you need to do this kind of lookup in a large array a big number of times then it's recommended to flip the keys and values (using array_flip()) then use isset() or access the value using [].

In order to get a real improvement, large and big in the paragraph above should be counted in thousands. Otherwise, concentrate on optimizations where there really is something to optimize: database, disk access, remote APIs etc.

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.