2

I'm trying to find a key in an array that doesn't start with zero.

This is my not so elegant solution:

private $imagetypes = [
    1 => [
        'name' => 'banner_big',
        'path' => 'campaigns/big/'
    ],
    2 => [
        'name' => 'banner_small',
        'path' => 'campaigns/small/'
    ],
// ...

If i use $key = array_search('banner_big', array_column($this->imagetypes, 'name')); the result is 0

I came up with this solution but I feel like I needlessly complicated the code:

 /**
 * @param string $name
 * @return int
 */
public function getImagetypeFromName($name)
{
    $keys = array_keys($this->imagetypes);
    $key = array_search($name, array_column($this->imagetypes, 'name'));
    if ($key !== false && array_key_exists($key, $keys)) {
        return $keys[$key];
    }
    return -1;
}

Is there a better solution then this.

I can't change the keys in.

3 Answers 3

2

Just save indexes

$key = array_search('banner_big',
                     array_combine(array_keys($imagetypes),
                                    array_column($imagetypes, 'name')));

demo on eval.in

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

Comments

0

The problem is array_column will return a new array (without the existing indexes)

So in your example.

$key = array_search('banner_big', array_column($this->imagetypes, 'name'));

var_dump($key);

//$key is 0 as 0 is the key for the first element in the array returned by array_column.

You can mitigate against this by creating a new array with the existing keys.

Comments

0

That's because array_column() generates another array (starting at index zero), as you may have imagined. An idea to solve this would be to transform the array with array_map(), reducing it to key and image name (which is what you're searching for). The keys will be the same, and this can be achieved with a simple callback:

function($e) {
    return $e['name'];
}

So, a full implementation for your case:

public function
getImagetypeFromName($name)
{
    $key = array_search($name, array_map(function($e) {
        return $e['name'];
    }, $this->imagetypes));

    return $key ?: -1;
}

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.