4

I'm trying to append a number of NULL characters '\0' to a string in PHP.

$s = 'hello';
while(strlen($s) < 32) $s .= '\0';

However, PHP adds 2 characters (\ and 0), instead of escaping the character and adding NULL. Does anyone know to add a NULL character to a string?

5
  • .= null; maybe? Will result in an endless loop though. Commented Jul 30, 2015 at 8:33
  • Nope, adding null does not increase the string length. Hence, the loop is infinite. Commented Jul 30, 2015 at 8:35
  • 1
    There is no NULL character in this world Commented Jul 30, 2015 at 8:36
  • str_pad($s, 32, "\0"); Commented Jul 30, 2015 at 8:37
  • 1
    single quoted strings do not interpret most \ escape sequences. '\0' is literally the string \0, whereas "\0" is the null character. Commented Dec 29, 2023 at 15:44

5 Answers 5

10

I don't know if \0 is correct in your case, but you should use ":

$s = 'hello';
while(strlen($s) < 32) $s .= "\0";
Sign up to request clarification or add additional context in comments.

3 Comments

well, well, well. That worked. I thought ' and " are synonyms in PHP?
Thanks. Learned something new.
5

Caused by ' you should use ".

Using simple quote PHP doesn't interpret code or special char like (\n\r\0), by using double quote PHP will.

Comments

3

This appears to work:

$result = str_pad($str, 32, "\0");
echo strlen($result); // output: 32

Comments

0

Try the following code

echo $str="Hello "; echo ' Length : '.strlen($str); while(strlen($str)<32) { $str.=' '; } echo '<br/>'; echo $str; echo ' Length : '.strlen($str);

Hope this will solve your problem

Comments

0

Just the following line is enough:

$s = pack('a32', 'hello');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.