1

I have an array called $myarray that might look like this:

Array
(
    [221] => suspended-suspended-1
    [691] => knee-ir-1
    [812] => knee-ir-4
)

Below, I am checking to see if an id exists as a key (691 for example) and if so, I then want to do another check to see if the string "ir" exists for that key. Not just anywhere in the array, it has to be next to 691, for example (i.e. on the specific line).

$row['id']=691; //for example

if (array_key_exists($row['id'], $myarray)) {  
    if (in_array("ir", $myarray)){
        //ill do some stuff here if "ir" exists         
    } else {
    }
}

Obviously, what I wrote will look for "ir" anywhere in the array, but how do I look only within the info associated with key "691"?

1

2 Answers 2

3

Use isset() and strpos() to simplify your code

$row['id']=691; //for example

if(isset($myarray[$row['id']]) && strpos($myarray[$row['id']],"ir") !==false){
  //ill do some stuff here if "ir" exists 
}

Output:-https://3v4l.org/5CrLW

Note:- if you want to check exact value on that index (that is given index value is ir or not)the use ==

Output:-https://3v4l.org/U7bHg

Sign up to request clarification or add additional context in comments.

1 Comment

In PHP7 if(strpos($myarray[$row['id']] ?? "","ir") !==false){ is even simpler
1
$myarray = Array(
            [221] => suspended-suspended-1 
            [691] => knee-ir-1 
            [812] => knee-ir-4 
            ); 
    if(isset($myarray){ 
        if (in_array("-ir", $myarray)) { 
            //ill do some stuff here if "ir" exists 
        }else{ 
            //ill do some stuff here if "ir" exists 
        } 
    } 
}

Comments

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.