Jump to content

Recommended Posts

Ok to keep this brief, i have a field where a user starts to type up a name and per letter entered it runs an ajax script that pulls info from database and suggests name such as  "John Doe". This works great but it has a little bug where as you type John, it will pull up all the johns but once you hit "John (space) and a letter (D in this case)" the script goes blank because of the query not being able to look it up properly because nobody will have a first or last name John D. So my idea is to split the name by the space using explode and then compare both strings "John" and "Doe" against first and last names. But im having a silly little issue.

 

I'm having a little explode issue when the string does not have a " " space.

 

Here's a simplified code just to point out my issue.

error_reporting(E_ALL);
ini_set('display_errors', '1');

$mystring = "This";

if(explode(" ", $mystring))
{
	$boom = explode(" ", $mystring);
	$first = $boom[0];
	$second = $boom[1];		

	echo $first . "<BR>";
	echo $second . "<BR>";
}
else
{
	echo "Sorry no spaces in the string";
}

 

And this rightufully returns an error:

Undefined offset: 1 in C:\Inetpub\wwwroot\Website\test\explode.php on line 14

 

which is the line >> $second = $boom[1]; simply because there is no $boom[1].

how can i check for a space before i allow that portion of the code to run.

 

Originally i though if(explode(" ", $mystring)) would do the trick by failing if there is no " ".

 

Silly i know. Thanks!

 

PS: How come my code is never colorfull when i post php code?

<?php

error_reporting(E_ALL);
ini_set('display_errors', '1');

$mystring = "This";

//$boom = explode(" ", $mystring);

if(explode(" ", $mystring))
{
	$boom = explode(" ", $mystring);
	if($boom[0]) { 
	$first = $boom[0]; 
	echo $first . "<BR>";
	}

	if($boom[1]) { 
	$second = $boom[1]; 
	echo $second . "<BR>";
	}


}
else
{
	echo "Sorry no spaces in the string";
}


?>

 

returns : Undefined offset: 1 in C:\Inetpub\wwwroot\Newton\test\explode.php on line 18

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.