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++){
.
.
.
Related
This question already has answers here:
Notice: Undefined index when trying to increment an associative array in PHP
(6 answers)
Closed 4 months ago.
I want to increment a value of an array, which is potentially not existing yet.
$array = [];
$array['nonExistentYet']++; // Notice
Problem
This leads to a NOTICE.
Attempt
I found a way to do this, but its kinda clunky:
$array = [];
$array['nonExistentYet'] = ($array['nonExistentYet'] ?? 0) + 1;
Question
Is there a more human readable/elegant way to do this?
well i guess a more readable way would be to use if..else as,
$arr = [];
if(array_key_exists('nonExistentYet', $arr)) {
$arr['nonExistentYet'] += 1;
}
else {
$arr['nonExistentYet'] = 1;
}
If this is used often, you can define a little helper method, which also uses an interesting side effect...
function inc(&$element) {
$element++;
}
$array = [];
inc($array['nonExistentYet']);
print_r($array);
gives...
Array
(
[nonExistentYet] => 1
)
with no warning.
As you can see the function defines the parameter as &$element, if this value doesn't exist, then it will be created, so the function call itself will create the element and then it will just increment it.
My standard implementation for this is:
if (isset($array['nonExistentYet']))
$array['nonExistentYet']++;
else
$array['nonExistentYet'] = 1;
But this is one of the rarely scenarios where I use the # operator to suppress warnings, but only if I have full control over the array:
#$array['nonExistentYet']++;
Generally, it is not good to suppress warnings or error messages!
What you ask is a little vague,
Either the variable exists and you increment it, or it does not exist in this case you create it.
In another case suppose that you want to do it in a for loop, in this case you do not have to worry about the existence of the variable.
One way is ternary operator, which checks if array value exists:
$array['iDoNotExistYet'] = empty($array['iDoNotExistYet']) ? 1 : ++$array['iDoNotExistYet'];
Other one would be just rewriting it to if and else condition.
Let's say I have a function returning the following array:
function fruits(){
$arr = array('apple','orange','banana','pear');
return $arr;
}
And I'd like to assign the third and forth array elements to a variables without using of temporary variable:
list(NULL,NULL,$banana,$pear) = fruits();
This code will not work, but it will show the idea of the way I'd like to use list construction.
The reasons I'd like to use list is the following:
I use PHP 5.3 so construction like fruits()[2] will not work.
I can do more assigns within one line of fairly readable code
I'd like to skip temporary variables to reduce code size and increase its readability.
So is there any possibility to use list and skip some array elements?
php 5.5.14
function fruits(){
$arr = array('apple','orange','banana','pear');
return $arr;
}
list(,,$banana,$pear) = fruits();
echo $banana; // banana
Yes, you can skip elements: just omit the variable name:
list(,,$banana,$pear) = fruits();
PHP 7.1+
[,,$banana,$pear] = fruits();
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.
I've got an odd error in my PHP code regarding dynamic arrays.
The error outputted is:
Fatal error: Cannot use string offset as an array ... on line 89
This is a portion of my code, it is within a foreach loop, which is looping through settings in a database:
foreach($query->fetchAll() as $row)
{
if($site!=CURRENT_SITE_TEMPLATE)
{
$property = 'foreignSettings';
$propertyType = 'foreignSettingsTypes';
} else {
$property = 'settings';
$propertyType = 'settingTypes';
}
$this->$property[$row['variable_section']][$row['variable_name']] = $row['variable_value'];
settype($this->$property[$row['variable_section']][$row['variable_name']],$row['variable_type']);
$this->$propertyType[$row['variable_section']][$row['variable_name']] = $row['variable_type'];
}
For the sake of the example code, $site is 'admin' and CURRENT_SITE_TEMPLATE is 'admin'.
In addition, $foreignSettings, $foreignSettingsTypes, $settings, and $settingTypes are all defined as arrays in the class scope
The error is on line 89, which is:
$this->$property[$row['variable_section']][$row['variable_name']] = $row['variable_value'];
I originally thought it was because of the $property variable accesing the array, however, this looks like valid legal code in the PHP documentation ( http://php.net/manual/en/language.variables.variable.php in example #1)
Any help on this error would be appreciated.
Thanks
In your given example $property is a string. You are then trying to use that as an array. Strings only has numeric indexes (if you need to use as an array).
The problem is as follows: $this->$property[0] means you access the 0th place of $property which in your case would be the first letter of the string $property. Thus you end up with $this->f or $this->s.
with $this->$property[0][0] you would be trying to access the 0th place of the 0th place of the $property string what results in an error because you try to access the 0th place of the char s what is not possible since the char s can not be referenced as an array.
what you want is $this->{$propperty}[0][0] what means that you try to access the 0th place of the 0th place of the variable that has the name $propperty.
If accessing an undefined index of a null reference, PHP does not throw any errors.
<?php
$array = &$foo['bar'];
if ($array['stuff']) echo 'Cool'; // No PHP notice
$array['thing'] = 1; // Array created; $foo['bar']['thing'] == 1
$array['stuff']; // PHP notice
If $array wasn't a reference PHP would have complained on the first line.
Why doesn't it for references? Do I need bother with isset for null references, or is PHP complaining internally and not letting me know?
In your code $array is null. The following code will not give you a notice either:
$b = null;
if ($b['stuff']) echo 'cool';
This is strange, this comment in the documentation points to that fact.
You must raise your error reporting level. Your example $array['stuff'] will throw warnings about index not found. I often combine a test for key in with the evaluation so as to prevent those warnings:
if( array_key_exists("blah",$arr) && strlen($arr['blah']) > 0 ) {
; // do stuff here
}
I often combine variables in with array names because anytime I have to cut-n-paste copy code to the next section to do the same-ish thing, I'd rather make an array of variable names and then iterate through the variable names. The most absurd condition is when I have billing and shipping data to manipulate, where I'll have an array variable name $BorS or just $BS and then at the top, set $BorS="shipping"; and end up with really interesting statements like:
${$BorS."data"}[${$BorS."_addr1"}]=$input_array[$BorS."_address_line_1"];
Why not just do:
$array = array();