0
$a['id'] = 124;
$b['id'] = '124';

if ($a['id'] == $b['id']) {}

In this case I want id`s are equals. How to properly compare string and int as int? Is there elegant way?

6
  • 1
    Try if(if ($a['id'] == (int)$b['id']) {} Commented Dec 7, 2018 at 4:38
  • Your code works perfectly fine as it is. 3v4l.org/d2Oj3 Commented Dec 7, 2018 at 4:41
  • By the way, your code works fine. Commented Dec 7, 2018 at 4:41
  • It works, but I think it is uncorrect way Commented Dec 7, 2018 at 4:43
  • 1
    @searcherforthetrueth Since you are using == instead of ===, PHP will automatically convert the type of the second value as necessary for comparison. What you are doing is fine. Commented Dec 7, 2018 at 4:55

1 Answer 1

1

Parse the string value to integer like this:

if($a['id'] == (int)$b['id']) {    
    // notice `(int)` which will make the '124' to int 124
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, maybe is there another elegant way with a trick with php standard function something like compare('int', value1, value2)- maybe do you know function like array_reduce or something like these fictional examples for correct comparing two values?
Please just remove inner if condition.its not needed.

Your Answer

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