Jump to content

Switches: Case string contains?


mcfmullen

Recommended Posts

Okay, so I can't wrap my head around this and google isn't helping.

 

I have a variable, $item that can be set to any string based on a MySQL database.

 

I need to have php call up specific code only when $item contains the word "boat".

 

For example, $item can store either steamboat, steam boat, sailboat or battleship. If want some code to execute on steamboat, steam boat and sailboat but not battleship.

 

This is what I'm using:

<?php
if (strpos($item, 'boat') == true){
include("FoundInside.php");
}
?>

 

The code does not execute. If I set it to != true, the code does execute, but for every instance of $item, regardless of what it is set to.

 

So my question is, what am I doing wrong?

Link to comment
https://forums.phpfreaks.com/topic/208799-switches-case-string-contains/
Share on other sites

are you sure the code is not executing?

the code you've posted is correct, are you setting the $item variable correctly?

i.e this works

$item = "i like steamboats";
if (strpos($item, 'boat') == true){

exit("'Boat' was found");

include("FoundInside.php");
}

 

it will kill the script and echo 'Boat' was found when the string boat is found. Delete this line after you have that part of the code working then you can work on "FoundInside.php"

Actually:

 

strpos('boat', 'boat') does not == true.  It actually == 0 which evaluates to false.  But it is !== false, so swap it and say:

 

if (strpos($item, 'boat') !== false) {
   //do the other something
} else {
   include("FoundInside.php");
}

Strpos never returns true, it either returns a number (the integer position of the found string) or false if it's not there.

 

Returns the position as an integer. If needle is not found' date=' strpos() will return boolean FALSE. [/quote']

 

So...your solution would be.

Actually:

 

strpos('boat', 'boat') does not == true.  It actually == 0 which evaluates to false.  But it is !== false, so swap it and say:

 

if (strpos($item, 'boat') !== false) {
   //do the other something
} else {
   include("FoundInside.php");
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.