It is necessary to check the presence of a character in a digit in a string, and if it does not exist, return a string with this digit, if there is a return string without it. I use the function:

$str = '1,2,3'; function get_str($str, $check) { $pos = strpos($check, $str); if ($pos === false) { return $str . ',' . $check; } else { return $str; } } echo get_str($str, 1); echo get_str($str, 4); 

But it does not work correctly. Tell me how you can realize your plans.

The following code returns:

 1,2,3,1 1,2,3,4 

Need to:

 1,2,3 1,2,3,4 
  • And what exactly is the "wrongness" of the function? Give specific input / output examples and your expectations. - Dmitriy Simushev
  • 1,2,3,1 1,2,3,4 - that's what happens - t16bz
  • one
    Arguments strpos should be the opposite - splash58
  • one
    @ splash58, read the documentation : If the needle is not a string, it is coded and interpreted as a character code. - Dmitriy Simushev
  • one
    @Dmitriy Simushev about the benefits of reading the documentation :) - splash58 pm

2 answers 2

First, the strpos arguments need to be swapped.

Secondly, you must pass a string to strpos, so either wrap the numbers in quotes or convert the function itself to a string.

 $str = '1,2,3'; function get_str($str, $check) { $pos = strpos($str, (string)$check); if ($pos === false) { return $str . ',' . $check; } else { return $str; } } echo get_str($str, 1); echo get_str($str, 4); 

returns:

 1,2,3 1,2,3,4 

But in general, it will be more convenient to convert everything into an array and work with it:

 $str = '1,2,3'; function get_str($str, $check) { $arr = explode(',' , $str); // преобразовать строку в массив $pos = array_search($check, $arr); //ищем элемент в массиве if ($pos === false) { $arr[] = $check; // добавляем return implode(',', $arr); //возвращаем строку } else { unset($arr[$pos]); //удаляем (я как понял, если есть то надо удалить) return implode(',', $arr); //возвращаем строку } } 

    Not bad with a regular schedule (we check that $ check is a digit that is not in $ str):

     $str = '1,2,3'; function get_str($str, $check) { if(preg_match("/^\d$/", $check) && (preg_match("/$check/", $str)==0)){ return "$str,$check"; } return $str; } echo get_str($str, "fake")."<br>"; echo get_str($str, 1)."<br>"; echo get_str($str, 4); 

    Results:

     1,2,3
     1,2,3
     1,2,3,4