Undefined offset error, but offset is not undefined - php

I'm getting:
Notice: Undefined offset: 0
in my code, however I can print_r the element I am trying to get and its clearly defined.
function get_members($entries_found) {
$members = $entries_found[0]['member'];
...
}
If I print_r($members) I get the expected output, however I'm still getting the Notice.
Any clues?

Do
var_dump($entries_found);
To check that the array does indeed have an offset of zero. Other things you can try would be reseting the array pointer
reset($entries_found);
of checking if it's set first
if (isset($entries_found[0]['member'])) // do things
If all else fails you could just supress the notice with
$members = #$entries_found[0]['member'];

I don't really know what happens with your $entries_found before accessing it from get_members
But i had the same problem. print_r and var_dump showed me, that the index exists but when i tried to access it i got the offset error
In my case i decoded a json string with json_decode without setting the assoc flag.
// Not working
$assocArray = json_decode('{"207":"sdf","210":"sdf"}');
echo $assocArray[207];
// working witht the assoc flag set
$assocArray = json_decode('{"207":"sdf","210":"sdf"}', true);
echo $assocArray[207];
Got my solution from here: Undefined offset while accessing array element which exists

Related

PHP variables variable not displaying if passed as an array or object

This works with simple variables. But it shows empty result with complex variables. AM I MISSING SOMETHING HERE? or is there anyother way around. Thanks.
#1. This works with simple variables.
$object = "fruit";
$fruit = "banana";
echo $$object; // <------------ WORKS :outputs "banana".
echo "\n";
echo ${"fruit"}; // <------------ This outputs "banana".
#2. With complex structure it doesn't. am I missing something here?
echo "\n";
$result = array("node"=> (object)array("id"=>10, "home"=>"earth", ), "count"=>10, "and_so_on"=>true, );
#var_dump($result);
$path = "result['node']->id";
echo "\n";
echo $$path; // <---------- This outputs to blank. Should output "10".
Not exactly using variable variables, but if you want to use a variable as the var name, eval should work
$path = "result['node']->id";
eval("echo $".$path.";");
From php.net's page on variable variables
A variable variable takes the value of a variable and treats that as the name of a variable.
The issue is that result['node']->id is not a variable. result is the variable. If you turn on error reporting for PHP notices you will see the following in your output:
PHP Notice: Undefined variable: result['node']->id ...
This can be solved as follows:
$path = "result";
echo "\n";
echo ${$path}['node']->id;
The curly braces around $path are required.
In order to use variable variables with arrays, you have to resolve an
ambiguity problem. That is, if you write $$a[1] then the parser needs
to know if you meant to use $a[1] as a variable, or if you wanted $$a
as the variable and then the [1] index from that variable. The syntax
for resolving this ambiguity is: ${$a[1]} for the first case and
${$a}[1] for the second.
If not present the statement is equivalent to
${$path['node']->id}
which will result in the following output:
PHP Warning: Illegal string offset 'node' in /var/www/html/variable.php on line 18
PHP Notice: Undefined variable: r in /var/www/html/variable.php on line 18
PHP Notice: Trying to get property of non-object in /var/www/html/variable.php on line 18

Undefined offset warning in php

I am doing this simple thing in php whenever i run the code i got an error
Notice: Undefined offset: 3 in C:\xampp\htdocs\colorconverter.php on line 37
this is the code that generated that error
function colorConverter($color)
{
preg_match_all("/(\d+\.+\d+)/", $color, $rgba);
list($rgba[0], $rgba[1], $rgba[2], $rgba[3]) = $rgba[1] ;
$rgbaValues = array("RED"=>$rgba[0], "GREEN"=>$rgba[1], "BLUE"=>$rgba[2], "ALPHA"=>$rgba[3]);
return $rgbaValues;
}
although it return correct value but why it still show an error
It should be because you do not have $rgba array with 4 elements from the beginning.
Preg match all returns 2 elements 0 and 1 where second (1) is array which I guess is $rgba[1][0], $rgba[1][1], $rgba[1][2] and so on. You are trying to override $rgba[1] with its child elements.
Either declare new array and fill it with 4 empty elements, or not apply array elements in list() there should be variables:
list($rgba1, $rgba2, $rgba3, $rgba4) = $rgba[1] ;

Illegal string offset warning when getting value out of array

There must be an obvious bug in this code but I'm not seeing it. Mind taking a look?
The below code returns
string
fleet
Warning: Illegal offset type (line 6)
The taskforces subroutine just pulls an .ini file, reads it into an array, and returns the array, which the foreach then iterates through. In relevant part, the array looks like this.
; this is an INI file
[scout]
type = "fleet"
Here is the code:
foreach($_SESSION['ini']->taskforces() as $key => $val)
{
echo gettype($val["type"]);
echo $val["type"];
if($val["type"] == "fleet") {
$commanderData[$val] = "BLOB";
$commanderData["sc$val"] = "INT NOT NULL";
}
}
I'd like to not have the illegal offset type, because I want the code to go through to the if condition. What obvious thing am I missing?
Thanks.
Instead of this:
echo $val["type"];
you should have simply:
echo $val;
Just because $val is not an array, it's a string. You've made a foreach through an array, so on each iteration you get an array key and an array value (which is, obviously, the string "fleet").
I'm not sure why this caused the problem, but I realized that the result of the if statement was not correct. The code
$commanderData[$val] = "BLOB";
attempts to use the matrix $val as the key for the $commanderData array. It should use the string $key from the iteration through the ini file. Once fixed, I stopped getting the warning, but it's not clear why this would have thrown the error on the proceeding line.

Undefined offset: 1 error coming from this line7

Every time I try to run my code I am getting a 'Notice: Undefined offset: 1 Error
specifically coming from this line:
$acmark= $summary[1][1] += $student[$row][2] / 25;
I am new to PHP and would like to get this working with the least amount of changes possible. I have uploaded the full source code to Pastebin to make for easier viewing.
http://pastebin.com/Ur8u673V
Thanks in advance guys, Luke.
Looking at the code in your paste, you're initialising $summary to an empty array, and never actually adding anything to it before attempting to read the data. It's equivalent to:
$summary = array();
// ...
$acmark = $summary[1][1] += $student[$row][2] / 25; // $summary[1] isn't defined
Agree with George - you're initializing $summary as an array, but the offset starts at 0. Since you're incrementing in a loop, change line 140 to:
$acmark = $summary[][] += $student[$row][2] / 25;
That will eliminate the notice. You can apply the same solution to the other lines with undefined offsets as well to resolve the other notices.
Consider using an associative array(s) with foreach loops so the array keys are more meaningful. Associative arrays are easier to use and support the idea of using self-documenting code
i think u should set value of array first (maybe with 0), because if undefines is meaning that array is null value (null is different with 0)
add this code after $summary = array(); like below
$summary=array();
//additional code
for($sum=0; $sum<6; $sum++)
$summary[$sum][1]=0;
for($row=0; $row<25; $row++){
.
.
.

How to check for offset in a loop

How can I check for a offset in cake php in a loop?, I have a message saying this...
Notice (8): Undefined offset: 1 [APP\views\cars\car_details.ctp, line 53]
Notice (8): Undefined offset: 2 [APP\views\cars\car_details.ctp, line 53]
Its in a foreach loop and retrieving items like this
$car_ratings['CarRating'][$j]['reccar_num']
Just run a check of array_key_exists() on the element like:
if(array_key_exists($j, $car_ratings['CarRating'])){
// true
}
Check the size of the array (using count()) then don't go over it.
For example:
for ($i = 0; $i < count($car_ratings['CarRating']); ++$i) {
// use the array at $i
}
Alternatively if you don't want to modify the loop, you can use array_key_exists() to determine if the array has a value defined for a particular key.
Of course using foreach would be better here.
If you could provide more context this answer might be better.

Categories