Jump to content

String to ASCII


boen_robot

Recommended Posts

Is there a build in PHP function that will take a whole string and convert it into a sequence of ASCII codes (perhaps in an array)? I guess I could write my own with a combination of ord() and explode(), like so (not tested):

function _stringToASCII($string) {	$estring = explode('',$string);	foreach ($estring as $char) {		$ascii[] = ord($char);	}	return $ascii;}

but I was hoping there's an existing function for that. Guess the reason... performance.

Link to comment
Share on other sites

Yeah, no existing function, but you can optimize yours a bit to make it quicker. For one, you can use array syntax with strings to access characters, so you don't need to use explode. You can use a for loop that initializes the return value and just have a loop and a return statement:

function _stringToASCII($string) {	for ($i = 0, $retval = array(); $i < strlen($string); $i++)		$retval[] = ord($string[$i]);	return $retval;}

Link to comment
Share on other sites

Neat. I never even suspected strings could be accessed as arrays. Thanks.But what difference does "for" make? Isn't "foreach" faster when used with arrays? If strings can be accessed as arrays, can't my first example work, but without explode() (but by explicitly casting $string to an array maybe)? And last but not least... if strings can be accessed as arrays, what is the point of using explode() oveall anyway, other then legacy support?

Link to comment
Share on other sites

I'm not sure about casting a string as an array, I've never tried doing that. I don't think that would work, I think casting a string as an array would create an array where the first element is the entire string. Foreach has a little more overhead then a normal for loop does (because for doesn't have to look at the array, foreach does), but the point with using for here is to get around using an array at all when we can just use the original string. I generally prefer to use a for loop anyway, but that's probably just a carryover from when I learned C, which doesn't have something like foreach.And, the point of using explode is for uses other then to just split up a string into characters, that is a special case where explode isn't necessary. If you want to split up the string around any other character or string, like a newline or comma, that's where you use explode.

Link to comment
Share on other sites

Archived

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

×
×
  • Create New...