PHP function Error : Notice: Undefined offset - php

I have simple function but got the error message : Notice: Undefined offset: 3 in
i checked the problem is in line : $newValue += $value[$i];
the answer of below function is "6" but error message still displayed.
<?php
function countMe($value) {
$newValue = 0;
for ($i=0; $i<=count($value); $i++)
{
$newValue += $value[$i];
}
return $newValue;
}
$value[0] = 1;
$value[1] = 2;
$value[2] = 3;
echo countMe($value);
?>
I know the solution is just Suppress the error with the # operator such as #countMe($value) but i want to know What's wrong with this function ?? Any help would be appreciated. Thanks

Indexes are from 0 to 2... your function should count to count() - 1:
for ($i=0; $i<=count($value)-1; $i++)
or
for ($i=0; $i<count($value); $i++)
By the way... just use array_sum($value) to get the same result :)

Please see that the value of count($value) is 3.
When you're mentioning <= in the loop, it's trying to access $value[3] but there's no such index available.
You could simply change it to <.
Another approach would be to use foreach instead. That provides more flexibility.
for ($i = 0; $i< count($value); $i++)
OR
foreach ($value as $v) {
$newValue += $v;
}
Hope this helps.

Related

Undefined offset: 0 after a loop using arrayholder in laravel 5.2

please help me figure this out. I just want to get the total quantity of the same inventory_record_id, as the image is shown below. And I wanted to store that total to an array name $salesQtyArrayHldr. However, it always return the undefined offset 0 error. Please help. Here is my code.
<?php
$salesQtyArrayHldr = array();
?>
#foreach($inventory as $val)
<?php
for($i = 0; $i < count($val->sales); $i++){
if($val->id == $val->sales[$i]->inventory_record_id ){
$salesQtyArrayHldr[$i] += $val->sales[$i]->quantity;
}
}
var_dump($salesQtyArrayHldr);
?>
Error
So check if isset:
if (isset($val->sales[$i])) {
// action...
}
Probably there is no such key in array $val->sales
Use helper dd() to check the structure of this variable.
for($i = 0; $i < count($val->sales); $i++){
if($val->id == $val->sales[$i]->inventory_record_id ){
if(isset($salesQtyArrayHldr[$val->id])){
$salesQtyArrayHldr[$val->id] += $val->sales[$i]->quantity;
}else{
$salesQtyArrayHldr[$val->id] = 0;
$salesQtyArrayHldr[$val->id] += $val->sales[$i]->quantity;
}
}
}

Removing duplicate entries in an array- Undefined offset error(PHP)

I am new to PHP and am trying to remove duplicate entries in an array. I end up with my desired output, but I am also getting two "Undefined offset" errors along the way. This is the code I have:
$this->master refers to an array declared in the beginning of the class.
public function removeDuplicates(){
$var = count($this->master);
for($i = 0; $i < $var; $i++){
for($j = 0; $j <$var; $j++){
if(($this->master[$i] == $this->master[$j]) && $i != $j){
$this->shiftLeft($j, $var);
$var --;
}
}
}
}
public function shiftLeft($t, $s){
while($t < $s){
echo "$t ";
$this->master[$t] = $this->master[$t+1];
$t++;
}
unset($this->master[$t-1]);
}
It is probably a really simple logical error but I cannot seem to find where. Any help is greatly appreciated.
See if it works
$unique = array_unique($this->master);

Undefined variable for loop

I have a code in use and it generates a PHP error in the second "for" loop.
PHP Notice: Undefined variable: newmatches
if (empty($result['ERR'])) {
preg_match_all('(<h3><a[^<>]*href="([^<>]*)"[^<>]*>(.*)</a>\s*</h3>)siU', $result['EXE'], $matches);
for ($i = 0; $i < count($matches[1]); $i++) {
$matches[1][$i] = urldecode($matches[1][$i]);
preg_match_all('/\*\*(http:\/\/.*$)/siU', $matches[1][$i], $urls);
$newmatches[1][$i] = $urls[1][0];
}
for ($i = 0; $i < count($newmatches[1]); $i++) { //PHP Notice: Undefined variable: newmatches
if(strstr($newmatches[1][$i], $domain))
return $i+1;
}
} else {
return '0';
}
Thank you in advance!
I don't see anywhere where $newmatches would be set, aside from the first for loop, which won't run if count($matches[1]) is 0.
Not sure what all this hardcoding of your index to 1 is about, but a simple fix is to set $newmatches[1] = array() before the first loop.

Notice: Undefined offset: 2

I'm new to php and I have done an example in php book. In there I got below notice. How to prevent this notice ?
<?php
require_once('AddingMachine.php');
$arrayofnumbers = array(100,200);
$objectname = new AddingMachine();
$objectname->addNumbers($arrayofnumbers);
?>
and
<?php
Class AddingMachine
{
private $total = 0;
function addNumbers(array $numbers)
{{
for($i=0;$i<=sizeof($numbers);$i++)
{
$this->total = $this->total + $numbers[$i];
}
echo $this->total;
}
}
}
Change your loop from
for($i=0; $i <= sizeof($numbers); $i++)
to
for($i=0; $i < sizeof($numbers); $i++)
Also preferable to use count.
for($i=0; $i < count($numbers); $i++)
The problem is with the <= sizeof($numbers) (which is equal to count($numbers). It will give you the total count of array elements, which is always one more than the maximum index, because arrays begin counting at 0.
Simply replace the <= with < and you'll be fine.

Undefined index errors when using plus equal operator

I'm working on another developers old code and there are tons of Notice: Undefined index errors when data is being set using the += operator. Essentially the index is not set yet in the array so the error is generated.
Example:
$myArray = array();
$myValue = 1;
for ($i = 1; $i <= 10; $i++)
{
$myArray['test'] += 1;
}
Will generate an error on the first run since the test index is not set yet.
I know I can remove this error with the following code:
$myArray = array();
$myValue = 1;
for ($i = 1; $i <= 10; $i++)
{
if ( ! isset($myArray['test']) )
{
$myArray['test'] = $myValue;
}
else
{
$myArray['test'] += $myValue;
}
}
However, there are around 50 of things like this to change. Is it worth writing all these isset statements or is there a better way I am not aware of?
EDIT: I should note that the array indexes aren't always the same and sometimes aren't set so I can't preset the index in this circumstance to avoid the error.
This is a bit shorter, but perhaps still a bit complicated if you have many edits.
$myArray = array();
$myValue = 1;
for ($i = 1; $i <= 10; $i++)
{
isset($myArray['test']) ? $myArray['test'] += $myValue : $myArray['test'] = $myValue;
}
You could also write a global function (not tested)..
$myArray = array();
$myValue = 1;
for ($i = 1; $i <= 10; $i++)
{
increment($myArray['test'], $myValue);
}
function increment(&$var, $inc){
$var = isset($var) ? $var += $inc : $var = $inc
}
If you are using PHP 7 and above, you can use the Null Coalescing Operator to make this code cleaner.
$myArray = [];
$myValue = 1;
for ($i = 1; $i <= 10; $i++)
{
$myArray['test'] = $myValue + ($myArray['test'] ?? 0);
}
The benefit here is not only that the code is cleaner, but you're also being more explicit about the default value (0)
Old/Deprecaded/Unrecommended but the shortest solution is
#$myArray['test'] += $myValue;

Categories