Jump to content

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");
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.