0

I am using the explode function in php to split a string like "60-5000" into two elements that can be cast to integers.

$parts = explode('-', '60-5000',2);

$this->p1 = (integer)$parts[0];
$this->p2 = (integer)@$parts[1];

When this is ran in the constructor of my class I am getting this error:

Undefined offset: 1

When I suppress the error on the second element of the array I obtain the correct array

0 => "60"
1 => "5000"

Above is the debug statement with error suppressed on the second index.

I do not want to keep having to suppress this error to get the results from explode. Is there something wrong with my implementation?

John Doe
  • 171
  • 1
  • 2
  • 6
  • Possible duplicate of [undefined offset when using php explode()](https://stackoverflow.com/questions/1807849/undefined-offset-when-using-php-explode) – Loek Jun 08 '18 at 13:35
  • 1
    Show more code. – u_mulder Jun 08 '18 at 13:37
  • 2
    [`explode()`](http://php.net/manual/en/function.explode.php) **does not** generate the `Undefined offset` notice. The code that uses `$parts` tries to access the value at a non-existent index and produces the notice when the string you split using `explode()` does not contain any `'-'`. `$parts` contains only one item in this case, at index `0`, `$parts[1]` does not exist and trying to access it for reading produces the notice. Check it out: https://3v4l.org/LTr03 – axiac Jun 08 '18 at 13:38
  • @axiac I beg to differ since when I suppress the error both array elements are given and there is always a '-' between two numbers – John Doe Jun 08 '18 at 13:58
  • working fine here : see https://eval.in/1017612 – Pradeep Jun 08 '18 at 14:00
  • Can you provide a sandbox where the issue is reproducible? I copied your code (changed only the names of the variables, it doesn't affect the behaviour) and it still works fine: https://3v4l.org/GE8Ac, https://3v4l.org/nCRjI – axiac Jun 08 '18 at 14:03
  • 1
    Closevote because not reproducible. @axiac has given the most fitting explanation, other possible causes might be: The notice comes from a completely different line/file, or, the symbol `-` is written in different variations, like `—`, `-`, `‐`, `‑` (those are all different symbols). You should write a test case for this. Keep one thing in mind: If the index does not exist, it does not exist. PHP does not lie to you. – Daniel W. Jun 08 '18 at 14:26
  • With suppression of errors I get what is expected with out I get the error. PHP is lying – John Doe Jun 11 '18 at 19:45

0 Answers0