1

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;
}
Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94
Roi
  • 27
  • 4

4 Answers4

1

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);
BeetleJuice
  • 39,516
  • 19
  • 105
  • 165
  • Just beat me to it! Nice. +1 – Jonathan Lam Aug 09 '16 at 13:05
  • can this works: $servicesTypes = array ( "hotel" => array ("HTL", "HTP", "HT"), "flight" => array ("FLT"), "m&a" => array ("APA"), "daily_tour" => array ("TOU"), "privat_car" => array ("PRC"), "transfer" => array ("4ST") ); – Roi Aug 09 '16 at 13:06
  • 1
    @Roi instead of complicating things, I would change the shape of the array to make them simpler. Look at my expanded answer. – BeetleJuice Aug 09 '16 at 13:11
1

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.
Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94
0

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');
rosengrenen
  • 731
  • 6
  • 21
  • There is nothing wrong with the `array()` syntax. Actually, it might [be preferred because it has older support](http://stackoverflow.com/a/17772560/2397327). – Jonathan Lam Aug 09 '16 at 13:15
  • This also doesn't answer the question at all. – Jonathan Lam Aug 09 '16 at 13:21
  • The answer is not supposed to focus on the array syntax, I used square brackers in my answer because that is the way I prefer. The thing I changed was the formatting of the array, which was improperly done for the usage, as I understand it. The function then loops throught each of the tags in each of the categories and returns the category in which the `$type` was found, else `returns false` – rosengrenen Aug 09 '16 at 17:03
0
$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; }

Swapnil Mahadik
  • 640
  • 5
  • 3
  • Welcome to Stack Overflow! While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! – Jonathan Lam Aug 09 '16 at 13:22