Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning: Cannot use a scalar value as an array in

Tags:

arrays

php

scalar

I am seeing the following error when executing my status script:

Warning: Cannot use a scalar value as an array in 

$result[$array[$i*2]] = $array[$i*2+1];

What am I doing wrong? I have included the full code below:

<?php 

// Set the host and port 
$host = "ip_goes_here"; 
$port = port_goes_here; 

// Open the socket connection to the server 
$fp = fsockopen("udp://".$host, $port); 

// Set the string to send to the server 
$string = "\xff\xff\xff\xffgetinfo"; 

// Set the socket timeout to 2 seconds 
socket_set_timeout($fp, 2); 

// Actually send the string 
fwrite($fp, $string); 

// Read the first 18 bytes to get rid of the header and do the error checking here 
if(!fread($fp, 18)) { 

      die("Oh God, the pain!"); 
} 

// Get the status of the socket, to be used for the length left 
$status = socket_get_status($fp); 

// Read the rest 
$info = fread($fp, $status['unread_bytes']); 

// Explode the result of the fread into another variable 
$array = explode("\\", $info); 

// Loop through and create a result array, with the key being even, the result, odd 
for($i = 0; $i < count($array)/2; $i++) { 

    $result[$array[$i*2]] = $array[$i*2+1];
} 

// Print the result for error checking 
print_r($result);     

// Close the file pointer 
fclose($fp); 

The line I mentioned is causing the errors. I have no idea what I am doing wrong here...

like image 994
Julian Martinez Avatar asked Feb 03 '14 09:02

Julian Martinez


People also ask

What is scalar value as an array?

The D language supports scalar arrays, which correspond directly in concept and syntax with arrays in C. A scalar array is a fixed-length group of consecutive memory locations that each store a value of the same type.

What is a scalar value in PHP?

Scalar variables are those containing an int, float, string or bool. Types array, object, resource and null are not scalar. Note: is_scalar() does not consider resource type values to be scalar as resources are abstract datatypes which are currently based on integers.

What's a scalar value?

A scalar value is simply a value that only has one component to it, the magnitude. For example, your speed is a scalar value because it only has one component, how fast you are going. Your height is also a scalar value because the only component is how tall you are. The same goes for your mass.


1 Answers

You can try declaring the variable $result, as an array, before using it.

$result = array();
// Loop through and create a result array, with the key being even, the result, odd 
for($i = 0; $i < count($array)/2; $i++) { 

    $result[$array[$i*2]] = $array[$i*2+1];
} 
like image 91
Havelock Avatar answered Sep 23 '22 04:09

Havelock