Undefined index errors when using plus equal operator - php

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;

Related

Declaring a variable dynamically in PHP

I need some variables in the following format:
$m_01;
$m_02;
$m_03;
.....
.....
.....
$m_12;
The digits in the variables are the months of the calendar.
I can declare 12 variables separately. However, I want to declare the variable using a loop. So I did something like this.
for($i = 1; $i <= 12; $i++) {
if($i<10)
$month = '0'.$i;
else
$month = $i;
$m_$i;
}
However, I am getting some error:-
Parse error: syntax error, unexpected '$month' (T_VARIABLE) in /var/www/html/custom/ci/Dotell_customer/application/controllers/login.php on line 412
How can I overcome this issue?
NOTE:
$$month creates a variable 01;
Is there any way where I can cave variable m_01?
P.S. I am aware of array. I just want to learn PHP variables variables.
This is not the best practise to follow, but still just for the answer:
for($i = 0; $i <= 12; $i++) {
${"m_$i"} = $i;
}
echo $m_1;
echo $m_2;
echo $m_3;
The best practise would be to create an array. For eg:
$arr = [];
for( $i=0; $i <=12; $i++ ) {
$arr['m_'.$i] = $i;
}
print_r($arr);
I think you are looking for something like
$varname = 'm_'.$i; // format the way you need it
$$varname = ...
As noted in the comments, it's rather a code smell, and often unnecessary. Typically an array does a better job, i.e.
$m[$i] = ...
Use PHP variable variables. This works as also suggested in the comments
${"m_$i"}
Going with Davids suggestion of using an array.
$month = [];
for($i = 1; $i <= 12; $i++)
{
if($i<10)
$month[] = '0'.$i;
else
$month[] = $i;
$month[$i];
}
here the $var[] = ... syntax appends your array. the $month[$i] accesses it.
Use of double variable is not usually suggested. You should really use an array to solve your problem as:
$month = array();
for($i = 1; $i <= 12; $i++)
{
if($i<10)
$month['m_0'.$i] = $i;
else
$month['m_'.$i] = $i;
}
otherwise if you really want to necessary go for double variable then :
for($i = 1; $i <= 12; $i++)
{
if($i<10)
${"m_0$i"} = $i;
else
${"m_$i"} = $i;
}
I hope it helps
for($i = 1; $i <= 12; $i++){
if($i<10)
$month = '0'.$i;
else
$month = $i;
$month = 'm_' . $month;
..........
}
Access var as
assignment $month = 'm_12';
value $$month

How to return array in php?

How to return array in php ? Actually I want to return whole value of $x[] insted of last index of $x[]. Please help me...
<?php
function top() {
require './php/connection.php';
$sql = "SELECT * FROM tbl_add";
$query = mysqli_query($connect, $sql);
$n = 0;
while ($result = mysqli_fetch_assoc($query)) {
$a[$n] = $result['add_id'];
$n = $n + 1;
}
$n = $n - 1;
for ($j = 0; $j < $n; $j++) {
for ($i = 0; $i < $n - 1 - $j; $i++) {
if ($a[$i] > $a[$i + 1]) {
$tmp = $a[$i];
$a[$i] = $a[$i + 1];
$a[$i + 1] = $tmp;
}
}
}
for ($i = 0; $i <= $n; $i++) {
echo $a[$i] . '<br>';
}
$j = 1;
for ($i = 0; $i <= 5; $i++) {
$r = $a[$i];
$sql = "SELECT * FROM tbl_add WHERE add_id='$r'";
$query = mysqli_query($connect, $sql);
$result = mysqli_fetch_assoc($query);
if ($result) {
$x[] = $result['mail'];
return $x[];
}
}
}
?>
return $x[]; is invalid syntax.
In expression $x[] = $result['mail'];, $x[] doesn't mean "the last element of $x". It is just a courtesy of PHP that spares the programmer of writing $x[count($x)]1 instead.
Returning an array is as easy as return $x; (given $x is an array).
Btw, there is no place in your code where $x is initialized as array. You just add values to some variable that doesn't exist, using the array syntax. PHP helps you and creates an array first and stores it in the $x variable but this practice is strongly discouraged. You should add $x = array(); somewhere before you use $x for the first time (outside the loop, of course). For example, you can put it before the line for ($i = 0; $i <= 5; $i++) {.
`
1 This statement is not entirely correct. However, if the values are added to the array using only the $x[] = ... syntax (as it happens in the posted code) then it is correct.
You have to return $x
Then when you call this function $data = top();
Now you get return data of function top to variable name data
// the code below will return $x as it is, independent of what it is. Array, integer, string etc..
Return $x;
// if you need to return two values use:
Return array($x, $y);
// again bit variables are returned as they are.
To call the function and get the values/array use:
$array = top();
Var_dump($array); //should be $x from your function

how to join two php variables to make one value

Is there any way to join two php value to make one word i have tried this code
PHP
for($n = 0; $n <= 2; $n++)
{
$check+$n = '<"strong">';
}
i want it to return some thing like
$check0 = '<"strong">';
$check1 = '<"strong">';
$check2 = '<"strong">';
joining the values of $n with $check
Your code puzzled me greatly at first. Basically, you want an array, like:
$check = array(); // make an empty array
for($n = 0; $n <= 2; $n++)
{
$check[$n] = '<"strong">'; //put stuff in each index
}
Variable variables:
<?php
for($n = 0; $n <= 2; $n++)
{
$varname = 'check' . $n;
$$varname = '<"strong">';
}
Notice the double $ in line 5.
http://php.net/manual/en/language.variables.variable.php
$check.$n will do the trick. You don't use a + like java but a .

Calculating sum in php

I'm a beginner in PHP and I was given the assignment to print out the harmonic series. Through my work, you can see that I have printed the correct algorithim for the harmonic series, but I can't seem to find a way to add them all up.
$total = 0;
if ($f1 = "proof") {
$i = $_GET["i"];
for($j= 1;$j<=$i;$j++) {
$total = $total +( 1/$j);
}
echo $total;
Thanks for your time
Thanks! It worked! Here is what I used
$i = 3;
$total = 0;
for($j= 1; $j<=$i ;$j++){
$total += $j/($j + 1);
}
echo $total;
As mentioned in the comments, the bug is here:
if ($f1 = "proof")
The = assigns the value of "proof" to the variable $f1 and doesn't evaluate equality like you want. What you really want is
if ($f1 === "proof")
which does an equality check. == works as well, it just doesn't check that types are the same (so 0=="0" evaluates to true, while 0==="0" would not)
Here is a shorter version:
<?php
$total = 0;
foreach(range(1, 3) as $v)
$total += $v/($v+1);
echo $total;
?>
Output:
1.9166666666667
BTW: In your if statement you make a assignment! You don't compare! you would have to use == OR ===

Correct way of php concatenation

Hey is this the correct way to do concatenation? it does not seem to want to work for me!.
$driver1points = 0;
$driver2points = 0;
$driver3points = 0;
$driver4points = 0;
for($i = 1; $i <= 4; $++){
if(${"driver".$i} == $driverrace["fastestlap"]) {
${"driver". $i ."points"} += $driver_points_system["fastestlap"];
$racepoints += $team_points_system["fastestlap"];
break;
}
}
I agree with what is said in the comments. An array is a much better way to handle this.
<?php
$driver1points = 0;
$driver2points = 0;
$driver3points = 0;
$driver4points = 0;
for($i = 1; $i <= 4; $++) {
$driver = "driver$i";
if($$driver == $driverrace["fastestlap"]) {
${$driver."points"} += $driver_points_system["fastestlap"];
$racepoints += $team_points_system["fastestlap"];
break;
}
}
Can be translated into:
<?php
$drivers['bill'] = 0;
$drivers['ted'] = 0;
$drivers['cheech'] = 0;
$drivers['chong'] = 0;
foreach ( $drivers as $driver => &$points ) {
if ( $driver == $race['fastestlap'] ) {
echo "$driver had the fastest lap!";
$points += $driver_points_system['fastestlap'];
$racepoints += $team_points_system['fastestlap'];
break;
}
}
You can obviously do this as a numerative array and replace all of the $drivers[$driverName] assignments to just $drivers[]. I used an associative array to demonstrate that arrays are not only more efficient for this application, they can also be much easier to work with.
I passed the value argument of the foreach by reference, the "&" prefix (similar to a pointer, variable stores the memory address as opposed to the value); this allows you to directly manipulate the value in your logic as opposed to being given a copy of the value and needing to reassign with something similar to a $drivers[$driver] = $points;

Categories