Undefined offset 0 - php

I have problem with this error script.
private function setCentroidCluster(){
for ($i=0;$i<count($this->centroidCluster);$i++){
$countObj = 0;
$x = array();
for ($j=0;$j<count($this->objek);$j++){
if ($this->objek[$j]->getCluster()==$i){
for ($k=0;$k<count($this->objek[$j]->data);$k++){ // Error
$x[$k] += $this->objek[$j]->data[$k];
The error is:
Notice: Undefined offset: 0
Notice: Undefined offset: 1
The error in line:
$x[$k] += $this->objek[$j]->data[$k];

First:
$x is an empty array. You want to add something at index $k. This is undefined. You need to define at least something there. There's a diff between auto-assigning array values and incrementing an existing array element:
for ($k=0;$k<count($this->objek[$j]->data);$k++){
if ( !isset($x[$k]) )
$x[$k] = 0; // depending on the type of data[$k] !!!
$x[$k] += $this->objek[$j]->data[$k];
}
should do the trick.
And as a recommendation, make yourself familiar with foreach:
foreach ($this->objek as $obj => $dat )
{
if ( $obj->getCluster() == $i )
{
foreach ( $dat as $datelem )
....
etc.

Related

How to update array based on values in another array

I get the error Undefined index: item_total on the line $totals['item_total'] += (float)$quantity; I want $totals array to contain the $mycart summarized quantity data by Product.
$mycart = array();
$mycart[0]['product'] = 'ProductA';
$mycart[0]['quantity'] = 10;
$mycart[1]['product'] = 'ProductA';
$mycart[1]['quantity'] = 4;
$mycart[2]['product'] = 'ProductB';
$mycart[2]['quantity'] = 8;
$mycart[3]['product'] = 'ProductB';
$mycart[3]['quantity'] = 8;
$totals = array();
foreach ($mycart as $row)
{
$product = $row['product'];
$quantity = $row['quantity'];
$totals['item_total'] += (float)$quantity;
}
In php you can create an array index by $totals['item_total'] = value;. And you cannot use an array index in an expression if it has not been "initialized". What do you see when you write this statement out $totals['item_total'] += (float)$quantity; "long hand"? It is just a shortcut for $totals['item_total'] = $totals['item_total'] + (float)$quantity;. In the right-hand expression $totals['item_total'] has not been initialized, thus program gives "Undefined index" message.
Your problem comes from using increment with an undefined variable
$totals['item_total'] += (float)$quantity;
The reason for this is that increment does a read (to get the current value) of the variable, before increment it. Which makes sense because we need to know it's current value before we can add 1 to it.
Now because that variable is not defined, you get an error message Undefined index: item_total". Which also makes sense because we cannot get the value of something (read it) that has not been defined, because it doesn't exist yet.
To further illustrate this, we can manually increment without the += like this:
$totals['item_total'] = $totals['item_total'] + 1;
We should agree this is the same as $totals['item_total'] += 1 as they give the same value, but here you can see how we must reference the previous value of that variable, which is the same thing that += must do. And in the same line of reason we cannot read it if it's not defined.
#Psudo for $var = $var + 1
write = read + 1
When simply assigning like this:
$totals['item_total'] = 0;
There is no reading (of an undefined value, as we know what 0 is) that takes place, so PHP is fine with that variable not existing and just creates it. Some languages are not that forgiving. What I mean here is some languagues you would need to first define $totals as an array, and then add stuff to it. In PHP $totals doesn't even need to exist to do $totals['item_total'] = 0;
So as others noted you need to define it with a value of 0 before hand, that way when the read is done it will know it's 0 and you wont see the error.
$totals['item_total'] = 0;
//or $totals = ['item_total' => 0];
foreach ($mycart as $row)
{
$product = $row['product'];
$quantity = $row['quantity'];
$totals['item_total'] += (float)$quantity;
}
echo $totals['item_total'];
Output
30
Sandbox
PHP is actually very forgiving about undefined variables, but in cases where it must first read that variable, it must be defined beforehand.
UPDATE
Based on this comment
I want it summed by product -- ProductA = 14 and ProductB = 16.
You can do it this way:
$mycart = array();
$mycart[0]['product'] = 'ProductA';
$mycart[0]['quantity'] = 10;
$mycart[1]['product'] = 'ProductA';
$mycart[1]['quantity'] = 4;
$mycart[2]['product'] = 'ProductB';
$mycart[2]['quantity'] = 8;
$mycart[3]['product'] = 'ProductB';
$mycart[3]['quantity'] = 8;
$totals = array();
foreach ($mycart as $row)
{
$key = $row['product'];
if(!isset($totals[$key])){
$totals[$key] = $row;
// $totals[$key] = $row['quantity']; //just [key=>quantity] no inner array
}else{
$totals[$key]['quantity'] += $row['quantity'];
// $totals[$key] += $row['quantity']; //just [key=>quantity] no inner array
}
}
print_r($totals);
Output
Array
(
[ProductA] => Array
(
[product] => ProductA
[quantity] => 14
)
[ProductB] => Array
(
[product] => ProductB
[quantity] => 16
)
)
/*
without the inner array
Array
(
[ProductA] => 14
[ProductB] => 16
)
*/
Sandbox
See my comments in the code on how to remove the inside array if you want just the Key and it's total quantity. If you do want the inner arrays but not the top level key (product), you can do this to remove those.
//after the loop
$totals = array_values($totals); //resets array keys to numbered keys
This will replace the ProductA and ProductB keys with 0 and 1.
Enjoy.
Simply add this line right before foreach:
$totals['item_total']=0;

Calculate the array name PHP

I have a large number of arrays
arrawithvalues0
arrawithvalues1
arrawithvalues2
arrawithvalues3
......
arrawithvalues999
Therefore I would like to calculate the name of the array to use in my script
I am using this code:
$secondarray = array();
for($iii = 0; $iii < 1000; ++ $iii) {
$array3 = "arrawithvalues" . $iii;
for($II = 0; $II < 10; ++ $II) {
array_push ( $secondarray, $$array3[$II]);
}
}
But get errors like this
Notice: Undefined variable: a in xxxxxxxxx on line xx
Notice: Undefined variable: r in xxxxxxxxx on line xx
Notice: Undefined variable: r in xxxxxxxxx on line xx
Thanks for reading and help
Use braces, like this:
array_push ( $secondarray, {$$array3}[$II]);
Right now, your code is being interpreted as this:
array_push ( $secondarray, ${$array3[$II]});
which is why you are getting those errors.

I'm receiving Undefined offset error

Why do I receive Undefined offset error? I'm trying to add 10,20,20 for each element in array. Please help. Thanks in advance
<?php
$arr = array("a","b","c");
$counter = 0;
$status = array();
foreach($arr as $a){
$status[$counter] += 10;
$status[$counter] += 20;
$status[$counter] += 20;
echo $status[$counter]."<br>";
$counter ++;
}
?>
Error:
Notice: Undefined offset: 0 in C:\xampp\htdocs\test\index.php on line 6
300
Notice: Undefined offset: 1 in C:\xampp\htdocs\test\index.php on line 6
300
Notice: Undefined offset: 2 in C:\xampp\htdocs\test\index.php on line 6
300
`
you are trying to add 10 in a undefined array element in this line:
$status[$counter] += 10;
try like this:
$arr = array("a","b","c");
$counter = 0;
$status = array();
foreach($arr as $a){
$status[$counter] = 10;//assign first
$status[$counter] += 20; //concate with assigned element
$status[$counter] += 20;
echo $status[$counter]."<br>";
$counter ++;
}
it should not provide any notices.
In your code, $status is an empty array, so when you attempt to add something to an undefined index you will see that notice (only for the first time).
To initialize $status as an array with values 0 based on the number of elements in $arr:
$status = array_fill(0, count($arr), 0);
You're using an 'add and assign' operator.
If you just want to assign a value then
$status[$counter] = 10;
Will work just fine.
However, you're asking PHP to add something to an existing element in your array, but there's no element there yet since you haven't initialised it. Just initialise your array before you start your loop.

Undefined offset 0, but still gives me correct result

$options = array('health', 'strength', 'agility', 'stamina', 'defence');
$total = array();
foreach ($options as $value)
{
foreach ($objects as $object)
{
$total[$value] += $object->$value;
}
}
var_dump($total);
I have some objects in an array called $objects. It's giving the data to the $total as it should do.
But by some reason it's whining about some undefined offset.
Notice: Undefined index: health in C:\wamp\www\objbattle\index.php on line 32
Line 32 is: $total[$value] += $object->$value;
Why!? And how do I get rid of it?
Because $total['health'] doesn't exist on the first iteration.
It's because you try to increment an uninitialized value. Try initalize them first.
$total = array('health' => 0, 'strength' => 0, 'agility' => 0, 'stamina' => 0, 'defence' => 0);
The key 'health' doesn't exist of the first loop through the for each. As a result you will get the notice.
You can do:
$total[$value] = 0;
Right above the second foreach.
Or, you could do it the lazy way and suppress the NOTICE:
error_reporting(E_ALL ^ ~E_NOTICE);
Why!?
I think because Sets which PHP errors are reported.
I expect because you are trying to increment an un-initialized value...
try assigning on the first round instead, like this:
$total[$value] = $object->$value;
or more simply, initializing the array values...
$total = array();
$total['health'] = 0;
etc...
or do it like #josmith suggests in his answer

Add key value to array without triggering an array

I've seen questions like this, but if I assign a key-value pair to an empty array lik this
$arr[$key] = $value;
I get the php notice
Notice: Undefined index: <key> in <path>
where of course <key> is whatever value was in $key.
How can I assign a value to a new key, without triggering a Notice?
Thanks!
edit: heres your more precise code. This is exactly whats in my code. Does this any difference?
while( list( $k, $sum ) = mysql_fetch_row( $res ) ) {
if( $sum < 0 ) {
$churn[$k] += $sum;
}
}
declare your array before addind the key
$arr = array();
$arr[$key] = $value;
or simply do
$arr = array($key=>$value);
what do you mean [$value]
You're trying to get the value of a brand new array with a given key
Your syntax isnt correct. Just try my quick testcase which wont throw any notice.
<?php
error_reporting(E_ALL);
$array = array();
$key = 'new_key';
$value = 'new_value';
$array[$key] = $value;
echo '<pre>';
var_dump($array);
exit;
?>
The problem layed in
while( list( $k, $sum ) = mysql_fetch_row( $res ) ) {
if( $sum < 0 ) {
$churn[$k] += $sum;
}
}
due to the += operator. The first time, it gets called, churn['whateverWasIn$k'] is not set. The second time is fine though.. So to get rid of the notices, it has to be like:
(!isset($churn[$k])) ? $churn[$k] = $sum : $churn[$k] += $sum;
Realize the missing + in the middle statement. So if this key does not exist by the time, i want to increase it by $sum, declare it and give it the value of $sum, otherwise just add $sum to the current value.
That's all. It doesn't look to pretty in code, but it gets me rid of 200 notices. Which also doesn't look too nice in my view.
Thanks for your help.

Categories