Roi Roi - 4 months ago 6
PHP Question

how to get array key by value? 2

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

Answer

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.