0

I have an array and I want to check if the key equals to a specific string, so I can use that information and give a new value to another variable $x, depending on which key is given.

So far I tried if (array_key_exists('slot1', $logoImages2)) {} (for example), but that does not seem to work.

So the array looks something like this:

'images2' => [
    'slot1' => 'images/Beutel.svg',
    'slot2' => 'images/Bund.svg',
    'images/Container.svg',
    'slot7' => 'images/DIY.svg',
    'images/Flasche.svg',
    'images/Sack.svg',
    'slot4' => 'images/Eimer.svg',
],

As you can see, some of the array items have a key and some do not have a key. Now I want to check, when a key is given, if the key is equal to a given value, like 'slot7' for example. So in theory I want to achieve something like this (this is just to explain my end goal):

foreach ($logoImages2 as $slot => $logo) {
    if (isset($slot)) {
        if (/* $slot is equal to 'slot7' */) {
           $x = $x2
        } elseif (/* $slot is equal to 'slot9' */) {
            $x = $x4
        }
    }
}
strayed soul
  • 67
  • 1
  • 7
  • ___So the array looks something like this___ NO!! Please show us EXACTLY what the array looks like. Try a `print_r($logoImages2);` – RiggsFolly Oct 25 '21 at 14:34
  • 1
    ___As you can see, some of the array items have a key and some do not have a key___ Well **NO!!** Some have assoc keys like `'slot1'` and the others will have **Numeric Keys** Its not possible to have an array item without a key :) – RiggsFolly Oct 25 '21 at 14:36
  • The keys will be `slot1, slot2, 0, slot7, 1, 2, slot4` – RiggsFolly Oct 25 '21 at 14:37
  • If this works `foreach ($logoImages2 as $slot => $logo) {` then your array does not look like you say – RiggsFolly Oct 25 '21 at 14:39

2 Answers2

1

You can foreach array and compare keys:

foreach ($logoImages2 as $slot => $logo) {
    if ($slot == "key_which_I_want") {
        $logoImages2[$slot] = $x2;
   }
   elseif (another condition) {
       $logoImages2[$slot] = $anotherVariable;
   }
}
Marty1452
  • 430
  • 5
  • 19
  • thanks a lot! I tried this and only used single equals but that didn't worked. But it works with the double or triple equals :) – strayed soul Oct 25 '21 at 14:39
1

You can foreach array and compare keys with value:

foreach ($logoImages2 as $slot => $logo) {
    if ($slot === "slot7") {
        $x = $x2
    } elseif ($slot === "slot9") {
        $x = $x4
    }
}
Simo OM
  • 139
  • 6
  • thanks a lot! I tried using this, but only used a single equals (=) so it didn't work, but it now works with the triple equals! :) – strayed soul Oct 25 '21 at 14:38