hihihihi
hihihihi

Reputation: 88

Compare strings regardless of leading or trailing spaces

I want to check if the data is match between array and the string. Im trying to check if the string is equals to each other but the problem is the condition is returning false and both value of $subex2[1] and $subdat is IT100. I think the problem is you can't compare an array to a string. Can someone help me about this?

here's the code

$subex = $objPHPExcel->getActiveSheet()->getCell('D8')->getValue();
$subex2 = explode(":", $subex);

$q = "select * from class where id='$id'";
$r = mysql_query($q);
$data = mysql_fetch_array($r);
$subdat = $data['subject'];

if ($subdat == $subex2[1]) {
    echo "Data matched";
} else {
    echo "Data doesn't matched";
}

Upvotes: 2

Views: 100

Answers (4)

Remco K.
Remco K.

Reputation: 717

As mentioned in the comments. One value has an space before it. You can solve this kind of problems like this:

if(trim($subdat) == trim($subex2[1])) {
    echo "Data matched";
} else {
    echo "Data doesn't matched";
}

for case sensitive issue, this trick should apply.

if(strtolower(trim($subdat)) == strtolower(trim($subex2[1]))) {
        echo "Data matched";
    } else {
        echo "Data doesn't matched";
    }

Upvotes: 1

yakupars
yakupars

Reputation: 26

try this:

$isMatched = strval($subex2[1]) === strval($subdat) ?: false;

Upvotes: 0

You first use array_map and trim values, delete space, next use in_array, example

$subex2 = array_map('trim',$subex2);

if( is_array($subex2) ){
     if(in_array($subdata, $subex2)){
         echo "Data matched";
      } else {
         echo "Data doesn't matched";
     }
 }

It's always good to check if it's actually an array, with is_array

Reference in_array https://www.w3schools.com/php/func_array_in_array.asp

Upvotes: 0

Thomas.L
Thomas.L

Reputation: 331

this test works fine

 $subdat = "IT100";
 $subex2[1] = "IT100";


  if($subdat == $subex2[1]) {
        echo "Data matched";

   }

You are not comparing same string

Upvotes: 0

Related Questions