I have this:
list($firstname, $lastname) = explode(' ', $queryString);
Sometiems $lastname does not gets defined, and it's there i am getting undefined offset error.
Because it can not find anything to put in $lastname, i guess.
After the explode() i have:
if(!$lastname) { $lastname = $firstname; }
So my question is how can i define it as the $firstname if $lastname is not defined (if you wrote only 'Adam' and not 'Adam Thompson', the lastname should be defined so it is 'Adam Adam')
It does this for me now, but I am receiving the offset error
The
2
inexplode()
ensures, that there are at most 2 values andarray_pad()
ensures, that there are at least 2 values. If there is no space character,
$lastname
isnull
. This you can use to decide what comes nextLittle update: For this specific case you can use a little trick
This will do all that in one step. It should work, because
$firstname
)$queryString == $firstname
. Thats now the value that is used to fill the array up to 2 values (which is exactly one, because one value we already have)$queryString
, because we already have 2 valuesAt least for readability I would prefer the first more obvious solution.
Try appending a space:
shouldn't have to change a thing after that.
I just ran into this today. my solution was not the above, (which had no effect) mine was the following:
instead of doing:
I'm not clear why this works, but the notice will go away. First, with this code I get the undefined offset notice:
However, with this code, I don't:
Also note, with '-' or '--' appended to $dateToChange, I will get the offset notice. It takes three dashes for it to go away in my example with four variables. $junk contains the two dashes (one being a separator).
You're not getting an Error, but a Notice.
Although this is acceptable since PHP is a dynamic language, you can prevent it with
isset()
:UPDATE
Per the comments,
list()
is the culprit for the Notice. In which case, I wouldn't recommend the use oflist()
whenexplode()
doesn't yield the appropriate number of parameters.If you must, the answer by brady or undefined offset when using php explode() can work. Although it's pretty ugly in my opinion. I believe your code would be much more intuitive if you just did the following: