Filter specific column in array in php

264
August 07, 2017, at 4:21 PM

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!

Answer 1

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:

  • http://php.net/manual/en/function.strpos.php

For an example, see:

  • https://3v4l.org/Ab4ud
Answer 2

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 compression operators

see strpos() docs

Answer 3

<?php
$event = ['categories' => 'meeting;skype'];
$needle = 'meeting';
$haystack = $event['categories'];
if( ($pos = strpos( $haystack, $needle )) === false){
   echo "\n$needle not found in $haystack";
} 
else
{
     echo "\n$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.

Rent Charter Buses Company
READ ALSO
Howto replace hyphen with shy inside paragraph with preg_replace

Howto replace hyphen with shy inside paragraph with preg_replace

How to search and replace hyphens within paragraphs to &shy?

205
application/json all requests going to 403

application/json all requests going to 403

Through postman, I am posting data to specific URL like sitecom/read_request

235
Bad performance in the cURL call on the same server

Bad performance in the cURL call on the same server

Why just few concurrency can cause block when cURL call on the same server

209
What is the best online quiz exam system using only php and mysql?Supported on 000webhost? [on hold]

What is the best online quiz exam system using only php and mysql?Supported on 000webhost? [on hold]

Help to find out pleaseand give me the whole project source code

199