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
        }
    }
}
4
  • So the array looks something like this NO!! Please show us EXACTLY what the array looks like. Try a print_r($logoImages2); Commented Oct 25, 2021 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 :) Commented Oct 25, 2021 at 14:36
  • The keys will be slot1, slot2, 0, slot7, 1, 2, slot4 Commented Oct 25, 2021 at 14:37
  • If this works foreach ($logoImages2 as $slot => $logo) { then your array does not look like you say Commented Oct 25, 2021 at 14:39

2 Answers 2

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
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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! :)
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;
   }
}

1 Comment

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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.