Roi
Roi

Reputation: 27

How to get array key by value?

I have array issue. This is my array:

$servicesTypes = array (
    "hotel"         => "HTL", "HTP", "HT",
    "flight"        => "FLT",
    "m&a"           => "APA",
    "daily_tour"    => "TOU",
    "privat_car"    => "PRC",
    "transfer"      => "4ST"
    );  

for each "type" i send i'm trying to get to key ("hotel", "flight", etc)

most of the time i get it, but for some values i get: "key: 0"

For instant, if type = "HTP" that key will be 0, for "HT" key will be "1".

Why is that?

This is my code:

function get_service_type ($servicesArray, $type)
{
    $key = array_search($type, $servicesArray);
    echo "key: ".$key;
    return $key;
}

I also tried this:

function get_service_type ($servicesArray, $type)
{

    foreach($servicesArray as $key => $service)
    {

        if ( $service == $type )
        {
            echo "key: ".$key;
            return $key;
        }
    }
   return false;
}

Upvotes: 1

Views: 1378

Answers (4)

BeetleJuice
BeetleJuice

Reputation: 40946

You are mistaken about the shape of your array.

  "hotel"   => "HTL", "HTP", "HT",

You think this is one array element, but it's actually 3 elements (array elements are separated by commas). When you don't provide a key for an array element, PHP chooses a key for you, starting with index 0, then 1...

So your get_service_type() function works as expected.

In response to your comment below:

Because you know the type (eg: HTP) and you need to find the category (eg: Hotel), the easiest way is to change how you build your array. Use keys the store the info you know. Eg:

[
    'HTL' => 'hotel',
    'HTP' => 'hotel',
    'HT' => 'hotel',
    'FLT' => 'flight',
    'APA' => 'm&a',
    ...
]

Then, your get_service_type becomes so simple that you don't really need a function anymore:

function get_service_type ($servicesTypes, $type){
    return $servicesTypes[$type];
}

If you also need access to just the categories (hotel, flight, m&a...) and you shaped the array as I recommend above, it's easy :-)

$categories = array_unique($servicesTypes);

Upvotes: 1

Swapnil Mahadik
Swapnil Mahadik

Reputation: 704

$servicesTypes = array (
"hotel"         => array("HTL", "HTP", "HT"),
"flight"        => "FLT",
"m&a"           => "APA",
"daily_tour"    => "TOU",
"privat_car"    => "PRC",
"transfer"      => "4ST"
); 

function get_service_type ($servicesArray, $type) {

foreach($servicesArray as $key => $service)
{
    if(is_array($service))
    {
        if(in_array($type,$service))
            return $key;
    }else
    {
         if ( $service == $type )
        {
           echo "key: ".$key;
           return $key;
        }
    }
}

return false; }

Upvotes: 0

Jonathan Lam
Jonathan Lam

Reputation: 17371

This is because the in following array initialization:

$servicesTypes = array (
  "hotel"         => "HTL", "HTP", "HT",
  "flight"        => "FLT",
  "m&a"           => "APA",
  "daily_tour"    => "TOU",
  "privat_car"    => "PRC",
  "transfer"      => "4ST"
);

You assign string keys to all of the values except HTP and HT. These items are assigned keys by default by PHP, which are 0, 1, and so on.

It seems that you want to assign the same key to multiple elements in PHP. This is not possible, however.


EDIT OP asked in below comments if it is possible to assign an array of values to every key. This is possible, but it will make the search function more complicated.

I.e., an array like this:

$servicesTypes = array (
  "hotel"         => array("HTL", "HTP", "HT"),
  "flight"        => "FLT",
  "m&a"           => "APA",
  "daily_tour"    => "TOU",
  "privat_car"    => "PRC",
  "transfer"      => "4ST"
);

in which the values can either be strings or arrays, can be found using a get_service_function() like this (cleaned up a bit):

function get_service_type ($servicesArray, $type) {
    foreach($servicesArray as $key => $service)
        if ( is_array($service) ) {
            foreach($service as $value)
                if($type == $value)
                    return $key;
        } else if ( $service == $type )
            return $key;
    return false;
}

What the above function does:

  1. Loops through $servicesArray
  2. If the $service is an array:
    • Loop through the $service.
    • If a match is found, return the key.
  3. Else if the $service is a string:
    • If a match is found, return the key.
  4. If no match, return false.

Upvotes: 1

rosengrenen
rosengrenen

Reputation: 781

You've formatted the array a bit wrongly and the code is changed with that (= [ ] is the equivalent of = array( )):

$servicesTypes = [
    'hotel' => [
        'HTL',
        'HTP',
        'HT'
    ],
    'flight' => [
        'FLT'
    ],
    'm&a' => [
        'APA'
    ],
    'daily_tour' => [
        'TOU'
    ],
    'private_car' => [
        'PRC'
    ],
    'transfer' => [
        '4ST'
    ],
];

function get_service_type ($servicesArray, $type)
{

    foreach($servicesArray as $key => $services)
    {
        foreach ($services as $service)
        {
            if ($service == $type)
            {
                return $key;
            }
        }
    }
    return false;
}

echo get_service_type($servicesTypes, 'HT');

Upvotes: 0

Related Questions