PHP: Define variables / array within a loop - php

I've got this code
$vote = array(
$arrayName[0][firstsector],
$termin[1][firstsector],
$termin[2][firstsector],
$termin[3][firstsector]
);
Now I want to create a loop for it. I tried this:
$howMuchIneed = 5;
for ($x = 0; $x <= $howMuchIneed; $x++) {
$vote = array(
$arrayName[$x][firstsector]
);
}
But the result doesn't look the same as the first code.

Have you tried this ?
for ($x = 0; $x <= $howMuchIneed; $x++) {
array_push($vote, $arrayName[$x][firstsector]);
}
initializes Array
$vote = array();
If you want to learn more about array_push http://php.net/manual/en/function.array-push.php

Try this (in your for loop):
$vote[] = $arrayName[$x]['firstsector'];
... and don't forget to declare your array before your loop!
$vote = array();
And in your first example you have 4 elements, condition in your for should be $x < 4 - arrays in PHP are zero-based.

Related

PHPWord addListItem loop corrupts the document

$cInc = json_decode($inc);
$c = count((array)$cInc);
for ($x = 0; $x < $c; $x++)
{
$section->addListItem($cInc[$x]);
}
So I want to loop the array $cInc to a List Item and somehow the loop corrupts the document.
i think you are wrong using count
The count() function returns the number of elements in an array
so you dont need array inside count
just
$cInc = json_decode($inc);
$c = count($cInc);
for ($x = 0; $x < $c; $x++)
{
$section->addListItem($cInc[$x]);
}
or u can use foreach if you dont know how many array that you have
$cInc = json_decode($inc);
foreach ($cInc as $val)
{
$section->addListItem($val);
}

PHP: Create Unique Variables In A For Loop

I was wondering if it is possible to create unique variables in a for loop using PHP. I tried the following code but it didn't work:
$level_count = 6
for ($i=1; $i<=$level_count; $i++) {
$level_ + $i = array();
}
I would like to end up with the variables $level_1, $level_2, $level_3, $level_4, $level_5 and $level_6. How would I achieve this?
$level_count = 6
for ($i=1; $i<=$level_count; $i++) {
$l = "level" . $i;
$$l = array();
}
But Zerkms is right...
$arr = array(array(),array(),array(),array(),array(),array());
It's much easier if you use arrays for this. Try this one-liner:
$level_count = 6;
$array = array_fill_keys(array_map(function($index) {
return 'level_' . $index;
}, range(1, $level_count)), array());
var_dump($array);
Weird thing (I have no idea why you want to use it), but, just for educational purposes...
$level_count = 6;
for ($i = 1; $i <= $level_count; $i++) {
$name = 'level_' . $i;
$$name = array();
}

Create arrays with cycles

I have the following code:
for ($i = 1; $i <= $j; $i++)
{
$goods_{$i} = array(
$_POST["'goods'.$i'_title'"],
$_POST["'goods'.$i.'_package'"],
$_POST["'goods'.$i.'_nmr'"]
);
}
I hoped that it could make this in first step of the cycle:
$i =1;
$goods_1 = array(
$_POST['goods1_title'],
$_POST['goods1_package'],
$_POST['goods1_nmr']
);
and so on in other steps.
I follow AbraCadaver's sentiments:
Why in the world are you doing this? You are using arrays, keep using them.
As such, I would write the code simply using an Array:
$goods = array();
for ($i = 1; $i <= $j; $i++)
{
// Assign to an index in the already created array,
// but DO NOT create a new variable.
$goods[$i] = array(
// Also make sure these are correct ..
$_POST["goods{$i}_title"],
);
}
If you really want to create dynamic variables - ick! - see variable variables.
Should be
$_POST["goods{$i}_title"],
$_POST["goods{$i}_package"],
$_POST["goods{$i}_nmr"]
It can be done like this:
for ($i = 1; $i <= $j; $i++)
{
${"goods_$i"} = array(
$_POST["'goods'.$i'_title'"],
$_POST["'goods'.$i.'_package'"],
$_POST["'goods'.$i.'_nmr'"]
);
}
You can read more about this topic in related PHP documentation.
The result of "'goods'.$i'_title'" will be 'goods'.1'_title', in case that you want it to be goods1_title then use following code instead:
for ($i = 1; $i <= $j; $i++)
{
${"goods_$i"} = array(
$_POST["goods{$i}_title"],
$_POST["goods{$i}_package"],
$_POST["goods{$i}_nmr"]
);
}
Another bug might be that in 1 case you use .$i. and in other 2 cases you use .$i without the last ..

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;

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