I am trying to filter a specific column in an array in php using the code below:
(strpos( 'meeting',$event['categories'] ) == false )
It is not working actually. An example of what [categories] hold is:
$event['categories'] = 'meeting;skype'
Thanks in advance!
You need to flip the arguments to strpos()
:
if (strpos($event['categories'], 'meeting') === false) {
echo $event['categories'] . ' does not contain "meeting"';
}
Also, use strict comparison (===
vs ==
), as meeting
could be at the start of the string, and then strpos()
would return 0
, which would evaluate to false
(which would be wrong in that case).
For reference, see:
For an example, see:
I think you should use ===
not ==
and also flip the arguments
(strpos($event['categories'] , 'meeting') === false )
strpos could return 0
or false
and when you use ==
then zero is like false
see strpos()
docs
<?php
$event = ['categories' => 'meeting;skype'];
$needle = 'meeting';
$haystack = $event['categories'];
if( ($pos = strpos( $haystack, $needle )) === false){
echo "
$needle not found in $haystack";
}
else
{
echo "
$needle exists at position $pos in $haystack";
}
See demo
The two things to watch out for are the order of the parameters for strpos() as well as doing a strict comparison using the identity operator ("===") so that when the 'needle' appears at position zero of the 'haystack' it's not mistakenly deemed a false result which occurs if you use the equality operator ("=="), given that in PHP zero == false.