1

I'm trying to check if one of my fields CONTAINS (rather than is equal to) an item grabbed from my $user variable. My field (field_targetuser) contains a string of numbers: 45, 409, 47, 100.

I'm trying to see if field_targetuser contains the grabbed uid (47). How should I be writing the below in order to accomplish this? Apologies for my newbness.

global $user;

if($user->uid == $data->field_targetuser)          
{
    return false;
} else {
    return true;
}
Brittany
  • 1,359
  • 4
  • 24
  • 63
  • Since it is a string you could use `strpos()` to find out if the specific number is in the string. – Jay Blanchard Mar 21 '19 at 16:31
  • 4
    Don't use a string operation for this. If you check for `47`, you'll also match `147`. Split the string into an array with `explode()`, then use `in_array()`. – Barmar Mar 21 '19 at 16:32
  • 1
    @JayBlanchard won't that be a problem with numbers like 'XX47' ? – Romain B. Mar 21 '19 at 16:33
  • Yes, of course it would be. I was making the assumption it was a well-known string. – Jay Blanchard Mar 21 '19 at 16:33
  • @Barmar Ahh that makes sense. How should this look then? PHP is fairly new to me... – Brittany Mar 21 '19 at 16:34
  • Is this list coming from a database column? You should probably normalize the schema. See https://stackoverflow.com/questions/3653462/is-storing-a-delimited-list-in-a-database-column-really-that-bad – Barmar Mar 21 '19 at 16:34
  • Then you would be able to match the uid in the database query. – Barmar Mar 21 '19 at 16:35
  • Also be careful as in your example `45, 409, 47, 100` there are spaces which if you use `explode()` will form part of the values in the array. You may need to `trim()` the values before `in_array()` will find anything. – Nigel Ren Mar 21 '19 at 16:39

2 Answers2

3

Use explode() with , parameter, which will make an array of the ids.

$arrTargetUserIds = explode(',', $data->field_targetuser);

Then find inside the array.

if(in_array($user->uid, $arrTargetUserIds)){
}
1

Usually PHP explode() to split your string as an array and in_array() to check the uid is within the exploded array. Also add array_map() to trim the white spaces around the numbers. Let's do it this way-

<?php
$user = new stdClass();
$data = new stdClass();
$user->uid = 47;
$data->field_targetuser = array_map('trim', explode(',', '45, 409, 47, 100')); 

if(in_array($user->uid,$data->field_targetuser))          
{
    print "Exists";
    return true;
} else {
    print "Not Exists";
    return false;
}
?>

DEMO: https://3v4l.org/NcbdW

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103