0

I'm having a tough time converting a value I read from socket connection into an integer. It's value tells me how many bytes are going to be received next.

$ar = fread($client, 4);
$binaryInt = unpack('N', $ar);
debug_to_console($binaryInt); //displays 16 (as expected)
$bred = fread($client, intval($binaryInt)); //intval returns 1

For some reason intval always evaluates to 1 and I can't figure out why. Btw the $ar variable is sent an integer from a java server I have running via this code sample

dOut.writeInt(data.length);

Thanks

edit

I finally got it. user2587326 below helped but instead of using intval(binaryInt[1]) it was just binaryInt[1].

3
  • We don't know what value you're looking at. Commented Dec 2, 2014 at 0:00
  • unpack returns an array. Calling intval on an array will always return 1 and emit a notice, so what you are seeing is perfectly normal. What are you trying to do actually? Commented Dec 2, 2014 at 0:08
  • This value tells me how many bits I'll be receiving after the 4 byte integer value I'm trying to evaluate. "$bred = fread($client, ...)" is where it's not evaluating to what I want Commented Dec 2, 2014 at 0:28

1 Answer 1

1

I think you are reading a 4-byte integer sent from your Java program over DataOutputStream to your PHP program over socket.

First, the fread($client, 4) call reads those 4 bytes as a string, then you convert them to an array with unpack(), taking 4-bytes at a time (format specifier 'N') thus resulting with an array with one element, so you just use:

intval($binaryInt[1]) instead of intval($binaryInt) to obtain that number.

edit: but it works with intval too, it won't hurt it.

Sign up to request clarification or add additional context in comments.

2 Comments

I got it, instead of using intval($binaryInt[1]) it's just $binaryInt[1]. $binaryInt[0] is the string value of the int in case anybody was wondering. php.net/manual/en/function.unpack.php under example #1 it is explained
You are correct, the intval() is not needed there. but $binaryInt[0] will not be available. You were confused by the example, which uses a different format specifier. In that case the array indexes are chars and int, not 0, and 1. The following example: <?php $x="1234"; $b=unpack('N', $x); foreach ($b as $key => $value) print "\$b[$key] = $value\n"; print gettype($b[1]) . "\n"; print $b[1] . "\n"; print $b[0]; ?> prints the following output: $b[1] = 825373492 integer 825373492 PHP Notice: Undefined offset: 0 in a.php on line 8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.