Krillko
Krillko

Reputation: 645

PHP: array search when array doesn't start on zero

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.

Upvotes: 2

Views: 323

Answers (3)

sidyll
sidyll

Reputation: 59297

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;
}

Upvotes: 0

Luke
Luke

Reputation: 3541

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.

Upvotes: 0

splash58
splash58

Reputation: 26153

Just save indexes

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

demo on eval.in

Upvotes: 2

Related Questions