Jump to content

[SOLVED] expoling a string with conditions.


iPixel

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

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.