Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - cannot use a scalar as an array warning

I have the following code:

 $final = array();     foreach ($words as $word) {         $query = "SELECT Something";         $result = $this->_db->fetchAll($query, "%".$word."%");         foreach ($result as $row)         {             $id = $row['page_id'];             if (!empty($final[$id][0]))             {                 $final[$id][0] = $final[$id][0]+3;             }             else             {                 $final[$id][0] = 3;                 $final[$id]['link'] = "/".$row['permalink'];                 $final[$id]['title'] = $row['title'];             }         }      } 

The code SEEMS to work fine, but I get this warning:

Warning: Cannot use a scalar value as an array in line X, Y, Z (the line with: $final[$id][0] = 3, and the next 2). 

Can anyone tell me how to fix this?

like image 991
zozo Avatar asked May 16 '11 15:05

zozo


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 PHP scalar value?

PHP includes two main types of variables: scalar and array. Scalar variables contain only one value at a time, and array variables contain a list of values. Array variables are discussed in the next section. PHP scalar variables contain values of the following types: Integers: whole numbers or numbers without decimals.

What is scalar value?

Definition: A scalar valued function is a function that takes one or more values but returns a single value. f(x,y,z) = x2+2yz5 is an example of a scalar valued function. A n-variable scalar valued function acts as a map from the space Rn to the real number line. That is, f:Rn->R.


2 Answers

You need to set$final[$id] to an array before adding elements to it. Intiialize it with either

$final[$id] = array(); $final[$id][0] = 3; $final[$id]['link'] = "/".$row['permalink']; $final[$id]['title'] = $row['title']; 

or

$final[$id] = array(0 => 3); $final[$id]['link'] = "/".$row['permalink']; $final[$id]['title'] = $row['title']; 
like image 180
brian_d Avatar answered Sep 19 '22 18:09

brian_d


A bit late, but to anyone who is wondering why they are getting the "Warning: Cannot use a scalar value as an array" message;

the reason is because somewhere you have first declared your variable with a normal integer or string and then later you are trying to turn it into an array.

hope that helps

like image 41
Lan Avatar answered Sep 17 '22 18:09

Lan