In C the last character of a string is always '\0' Is it same for PHP as well? If not, then what's the last character of a string in PHP?
for( $i = 0, $len = strlen( $string ); $i < $len; $i++ )
{
$char = $string[ $i ];
// do something with $char
}
... is one way to do it.
Another way, is simply using PHP function str_split()
(which creates an array of the individual characters of the string (unless you pass it the second argument $split_length
of a different length than the default)):
foreach( str_split( $string ) as $char )
{
// do something with $char
}
... etc.
Edit:
As an addendum to your comments to your question; use fgetcsv()
for parsing csv files.
To loop over the characters in a string, you write:
for (i = 0; i < strlen($string); i++) {
$char = substr($string, $i, 1);
// Do stuff with $char
}
Strings in PHP are binary safe, which means that they can contain \0
as well. Therefore, there's no termination character that could be used.
Instead, the length of the string is stored separately inside PHP's internal variable representation. This also makes string length calculations much faster.
i have a csv file containing some data for database.now i have to convert each line of data in sql format. the data in csv file is as follows:"abc,abc,1243,abc" I have to make them like thi s" 'abc','abc',123,'abc' ".
First of all, you should use fgetcsv()
for that; it turns the whole line (or lines in some cases) into one array.
I'm going to guess you want to store those values into a database; you could use this:
if ($arr = fgetcsv($f)) {
$stmt = $db->prepare('INSERT INTO tablename VALUES (?, ?, ?, ?)');
$stmt->execute($arr);
}
This assumes each line in your CSV has four items; to make it more generic you could use the length of $arr
to construct the number of place holders to add in the query.
I think its should be worked
$lastChar = substr($string, -1);