Removing duplicate entries in an array- Undefined offset error(PHP) - 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);

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;
}
}
}

PHP function Error : Notice: Undefined offset

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.

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.

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;

Accessing class variables with for loop

I would like to access class variables with for loop, here is my simple class
class test{
public $var1 = 1;
public $var2 = 2;
public $var3 = 3;
public $var4 = 4;
}
$class = new test();
this is how i try to access variables with a loop
for($i = 1; $i <= 4; $i++){
echo $class->var.$i;
}
and i get error which says
Notice: Undefined property: test::$var in C:\xampp\htdocs\test\index.php on line 12
Well it's not really a big error and i actualy get the value echoed but i still don't understand why do i get this error?
also if i do it this way everything works fine:
echo $class->var1;
for($i = 1; $i <= 4; $i++){
$var = 'var' . $i;
echo $class->$var;
}
Or, as mentioned in the comments, this will work in newer versions of PHP
for($i = 1; $i <= 4; $i++){
$class->{'var' . $i}
}
You're not actually getting the value echoed, you're getting $i echoed.
echo $class->var.$i; is being interpreted as echo ($class->var).($i);. Since var isn't a variable (hence the error), it becomes echo ''.$i;, so you get the value of $i. It just so happens that var1 has the value 1. (Change $var1 to something else, and you'll see what I mean)
To fix the issue, you can do this:
for($i = 1; $i <= 4; $i++){
$class->{'var'.$i}
}
The stuff inside the {} is calculated first, so the correct property is read.
The code isn't doing what you think. It's only echoing 1-4 because of your $i in the for loop. If you were to change the vars in the class, your output will still be 1-4.
The undefined property notices is the clue: it is trying to access the property var.
If you want to store data that is repetitive and/or associated, especially like in your example, it is usually more suitable to store as an array:
class test{
public $vars;
public function __construct()
{
$this->vars = array(1, 2, 3, 4);
}
}
$obj = new test();
foreach($obj->vars as $var)
{
echo $var;
}
The dot (.) operator is getting used by the echo rather than the member call to $class.
One of many solutions:
for($i = 1; $i <= 4; $i++){
echo $class->{'var'.$i};
}
live example here
This already works fine on very recent PHP versions, but try this:
for($i = 1; $i <= 4; $i++){
$v = 'var'.$i;
echo $class->$v;
}

Categories