Just read the first character of a string

Asked

Viewed 4,285 times

6

if ($myrow['Noticia'] !== '<' && $myrow['Noticia'] !== 'Nao') {
   echo "Noticia mal colocada!";
}

I have this code and I’d like you to just check the first character of the column Noticias that would be this < and if I didn’t have this character at first, and it was different from Nao , presented the message.

  • you can add the (s) example(s) of the correct string(s))?

  • $Myrow just get the columns from my table, nothing more..

  • but if you want to compare/analyze $myrow['Noticia'] You’re comparing/analyzing a string, right? My question is, what are the correct values $myrow['Noticia'] have inside you want to check. Gives example(s) of right and wrong cases to better understand the problem...

  • I’m sorry, but I don’t understand your question/question :

  • What I wanted was for PHP to just check if the column is < or not. if no message appears ..

  • So you want to check if the string starts with < right? and besides you want to check if it’s different from "No". Right?

  • All right, that’s right, buddy!

Show 2 more comments

2 answers

9


You can read the first character passing its index, as if it were an array:

$myrow['Noticia'][0]

Note: the $myrow['Noticia'][0] will generate a warning (notice) if the string value is null.

  • Thank you, it worked, you can enlighten me more about the [0]?

  • 2

    [0] says that you will pick up the character that is at zero position of the string (the first character). [1] take the second, and so on.

  • and for example, if you want to take the first two or the first and the third?

  • 2

    The first and the third you would need to take separately. If you want to take more than one in sequence, use a separate function for this like substr: http://php.net/manual/en/function.substr.php

6

Another alternative is the function substr:

if (substr($myrow['Noticia'], 0, 1) !== '<' && $myrow['Noticia'] !== 'Nao') {
   echo "Noticia mal colocada!";
}

Where substr ( string $string , int $start [, int $length ] ):

  • $string: The variable to be analyzed.
  • $start: Indicates the starting position at $string.
  • $length: The amount of characters that must be returned from $start.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.