I'm trying to create for loop giving strings empty value. How I can do it?
for ($i = 1; $i <= 24; $i++) {
$b2_ch_v = ${'b2_g_v_'.$i}['id'];
$$b2_ch_v = '';
}
/*
result should be:
$b2_g_v_1['id'] = '';
$b2_g_v_2['id'] = '';
[...]
$b2_g_v_24['id'] = '';
*/
Don't use variables named like $x1, $x2, $x3. You almost always want to use arrays instead. In this case, you can use an indexed array of associative arrays. This is sometimes also called a two-dimensional array.
for ($i = 0; $i < 24; $i++) {
$b2_ch_v[$i] = ['id' => ''];
}
Then your first element becomes:
$b2_ch_v[0]
And its named elements can be referred to via:
$b2_ch_v[0]['id']
You're setting $b2_ch_v to the current contents of the id element of the array, not a reference to the array element. You need to refer to the array index in the assignment.
for ($i = 1; $i <= 24; $i++) {
$b2_ch_v = 'b2_g_v_'.$i;
${$b2_ch_v}['id'] = '';
}
var_dump($b2_g_v_1); // => array(1) { ["id"]=> string(0) "" }
You don't actually need the variable, you can do the calculation in the assignment:
${'b2_g_v_'.$i}['id'] = '';
But it's best to avoid variable variables in the first place, and use arrays instead as in the other answer.
Related
Apologies for the dumb question, I just can't seem to understand what's exactly going on. I have a JS function which I transformed into PHP and in the JS everything is working as desired.
The problem with the PHP one is here I believe:
I have last element of and array which I get by
$lastPeriod = end($periods);
while being in a for loop.
Next I set the value of $lastPeriod['closeTime'] to equal a number. If I dd($lastPeriod) after changing it's value it is updated, however if I dd(); at the end it is not. Maybe there is a conflict with how I remove the next element so the end is not working correctly?
for ( $i = 0; $i < sizeof($dailyHours); $i++ )
{
$periods = $dailyHours[$i]['periods'];
for ($j = 0; $j < sizeof($periods); $j++)
{
$lastPeriod = end($periods);
if ($lastPeriod['closeTime'] === '00:00'
&& $dailyHours[$i + 1]['periods'][0]['openTime'] === '00:00'
&& $dailyHours[$i + 1]['periods'][0]['closeTime'] !== '00:00')
{
if (Carbon::parse($dailyHours[$i + 1]['periods'][0]['closeTime'])->isBefore(Carbon::createFromTimeString('11:59')))
{
$lastPeriod['closeTime'] = $dailyHours[$i + 1]['periods'][0]['closeTime'];
array_splice($dailyHours[$i + 1]['periods'], 0, 1);
if (sizeof($dailyHours[$i + 1]['periods']) < 1)
{
$dailyHours[$i + 1]['isOpen'] = 0;
}
}
}
}
}
}
The problem is that you are editing a copy of the array.
Let's look at this example:
<?php
$myPets = [
[
'animal' => 'cat',
'name' => 'john'
],
];
$pet = $myPets[0];
$pet['name'] = 'NewName';
var_dump($myPets);
When I run this program the name of my pet should be 'NewName' right?
array(1) {
[0]=>
array(2) {
["animal"]=>
string(3) "cat"
["name"]=>
string(4) "john"
}
}
Well, as you can see the name hasn't changed.
This is because when we do $pet = $myPets[0] PHP will make a copy of the $myPets[0] array.
To fix this you can take the reference of that array by doing:
$pet = &$myPets[0].
There are a few issues in the code:
In a loop you have this code:
$lastPeriod = end($periods);
Then later on you have:
$lastPeriod['closeTime'] = $dailyHours[$i + 1]['periods'][0]['closeTime'];
This should result in a warning
Warning: Cannot use a scalar value as an array in ....
The issue that $lastPeriod = end($periods); gives you the value of the last element in the array. So if you have this array:
$dailyHours[0]['periods'][] = 23;
$dailyHours[0]['periods'][] = 12;
$dailyHours[0]['periods'][] = 5;
$dailyHours[0]['periods'][] = 8; //Last elements value in item 0
$dailyHours[1]['periods'][] = 23;
$dailyHours[1]['periods'][] = 11;
$dailyHours[1]['periods'][] = 3; //Last elements value in item 1
$dailyHours[2]['periods'][] = 5;
$dailyHours[2]['periods'][] = 12; //Last elements value in item 2
Therefore
$lastPeriod = end($periods);
would return the values 8,3 and 12.
A simplified version of your code with two loops. The outer loop ($i) and the inner loop ($j)
for ( $i = 0; $i < sizeof($dailyHours); $i++ ) {
$periods = $dailyHours[$i]['periods'];
for ($j = 0; $j < sizeof($periods); $j++) {
$lastPeriod = end($periods); //would give 8,8,8, 3,3,3 and 12,12,12
//This would basically mean that an associative array with key closeTime
//with the value of 8,3 or 12 => is the same as the value of $dailyHours[$i +
//1]['periods'][0]['closeTime'];
//This is not a thing PHP can handle and therefore you should reviece
//a warning "Cannot use a scalar value as an array..."
//(You simply cannot mix numbers and associative arrays in that manner)
$lastPeriod['closeTime'] = $dailyHours[$i + 1]['periods'][0]['closeTime'];
}
}
Another issue is that you're trying to set a value each iteration with the same key and therefore nothing happens:
for ( $i = 0; $i < sizeof($dailyHours); $i++ ) {
$periods = $dailyHours[$i]['periods'];
for ($j = 0; $j < sizeof($periods); $j++) {
$lastPeriod['closeTime'] = rand();
echo '<pre>';
echo $lastPeriod['closeTime'];
echo '</pre>';
}
}
A possible output of the loops above code could be:
1393399136
1902598834
1291208498
654759779
493592124
1469938839
929450793
325654698
291088712
$lastPeriod['closeTime'] would be 291088712 which is the last set value above (last iteration) but the previous values set are not stored anywhere.
I need to create a php file with a hundred variables, which are all identical except for their id.
PHP Code
$var1 = get_input('myvar1');
$var2 = get_input('myvar2');
$var3 = get_input('myvar3');
$var4 = get_input('myvar4');
...
$var30 = get_input('myvar30');
I wonder if it is possible to create only one line as a model, and is replicated 30 times?
I think you are looking after something like this :
$vars = [];
for($i = 1; $i <= 30; $i++) {
$vars[] = get_input('myvar' . $i);
}
this is a job for arrays
$var = array_fill(1, 30, 'myvar');
use the array key as your "id"
Why bother with arrays when you can create the variables like so. The variables names are also set dynamically just like the values.
for ($i = 1; $i <= 100; $i++) {
${'var' . $i} = get_input('myvar' . $i);
}
I have some arrays extracted from a XML-file. These are in
$array0 = (.......)
$array1 = (.......)
...
$arrayN = (.......)
Now I need a single array with all arrays in it separated by "," as
$masterArray = array($array0,
$array1,
...
$arrayN)
I tried
for ( $i = 0; $i < N; $i++) {
$masterArray = $masterArray + $array[$i];
}
with no result. I tried array_merge but this will give one
$masterArray(......................all items of all $arrays.....)
How can I do it right?
for ( $i = 0; $i < N; $i++) {
$temp = "array".$i;
$masterArray[$i] = ${$temp};
}
Given your exact definition of what you got and what you want the routine should be:
for ( $i = 0; $i < N; $i++) $masterArray[] = ${'array'.$i};
Not much to explain here. You make a new entry in an array with $variable[] = <entry>; and you access your numbered array with a variable variable, see:
http://php.net/manual/en/language.variables.variable.php
I guess you wont to create a multi dimension array:
$masterArray = array();
$masterArray[] = $array0;
$masterArray[] = $array1;
...
$masterArray[] = $arrayN;
this will in all arrays as element of the MasterArray:
$masterArray[0=>(....),1=>(....), ...];
Then access it like this:
$arr1_key1 = $masterArray[1]['key1'] ; //$array1['key1'];
You can add specific keys if you wont:
$masterArray['arr1'] = $array1;
$arr1_key1 = $masterArray['arr1']['key1'] ; //$array1['key1']
In general read some more to get better understanding on how to work with arrays ;)
I have 2 arrays, both are multidimensional with same number of elements and same values, which are on different positions (those values are actually ID-s from my database, so one ID appears only once). How can I sort second array with values which are in first array?
For example - if first array looks like:
$array1[0][0] = 1;
$array1[0][x] = it doesn't matter what's here
$array1[1][0] = 4;
$array1[1][x] = it doesn't matter what's here
$array1[2][0] = 3;
$array1[2][x] = it doesn't matter what's here
...
how to sort second array so it would have same values as array1 on indexes [0][0], [1][0], [2][0], etc.
How I could solve problem is:
$i=0
while ($i < (count($array1)-2)){ // * check down
$find_id = $array1[$i][0];
// here I need to search for index of that ID in other array
$position = give_index($find_id, $array2);
// swapping positions
$temp = array2[$i][0];
$array2[$i][0] = $array2[$position][0];
$array2[$position][0] = $temp;
// increasing counter
i++;
}
function give_index($needle, $haystack){
for ($j = 0, $l = count($haystack); $j < $l; ++$j) {
if (in_array($needle, $haystack[$j][0])) return $j;
}
return false;
}
*There is only -2 because indexes start from 0 and also for the last element you don't need to check since it would be automatically sorted by last iteration of while-loop.
I don't find this solution good as I think that this is quite simple issue (maybe it's not even correct). Is there easier way in PHP that I'm missing?
This is the most efficient way I can think of:
function swap(&$a, &$b) {
$t = $a;
$a = $b;
$b = $t;
}
function find_index($id, $array, $from = 0) {
$index = false;
for ($i = $from, $c = count($array); $i < $c; $i++) {
if ($array[$i][0] == $id) {
$index = $i;
break;
}
}
return $index;
}
for ($i = 0, $c = count($array1); $i < ($c - 2); $i++) {
if ($array1[$i][0] != $array2[$i][0]) {
$fi = find_index($array1[$i][0], $array2, $i);
swap($array2[$i][0], $array2[$fi][0]);
}
}
What changes from yours?
I've defined a swap() function in order to swap any variable. That doesn't cost anything and makes everything look nicer. Also you can reuse that function later if you need to.
In the find_index (give_index in your code) we stop the loop once we find the correct index. Also we avoid the cost of an in_array function call.
We modified the find_index function to start only from the part of the array we haven't checked yet. Leading to a way more efficient way of scan the array.
In the for loop (a while loop was just wrong there) we stored the count of the array once, avoiding multiple calls.
Also we swap the $array2 values only if they are in the wrong place.
Other improvements
If you know anything else of the $array2 array you can make this even more performant. For example if you know that indexes are alternated like in $array1 you can change the main for loop from:
for ($i = 0, $c = count($array1); $i < ($c - 2); $i++) {
to
for ($i = 0, $c = count($array1); $i < ($c - 2); $i+2) {
(notice the $i+2 at the end) And you could do that in the find_index function as well.
Look into usort (http://php.net/manual/en/function.usort.php).
It provides a simple way to sort arrays using a user provided comparison function.
DESCRIPTION OF PROBLEM:What I am trying to do is pass dynamically created variables from a loop to a function in php. More specifically, I used a for loop to create variables and assign data to them. Then use a for loop to string all the variables together. Then pass the string to the multisort_array function and explode the string to use the variables. I'm not sure what I am doing wrong.
QUESTION:How would I pass a bunch of dynamically created variables to a sort function without knowing how many I am going to create? That is my delema.
CODE:
$arr2[0] = "100::HOMEDEPOT";
$arr2[1] = "200::WALMART";
$arr2[2] = "300::COSTCO";
$arr2[3] = "400::WALGREENS";
$arr2[4] = "500::TACO BELL";
// explodes first value of $arr2
$tmp = explode("::",$arr2[0]);
// determines how many dynamic variables to create
for($k=0;$k<count($tmp);$k++){
${"mArr".$k} = Array();
}
// loops thru & assigns all numbers to mArr0
// loops thru & assigns all names to mArr1
for ($k=0;$k<count($arr2);$k++){
$tmp = explode("::",$arr2[$k]);
for($l=0;$l<count($tmp);$l++){
${"mArr".$l}[$k] = $tmp[$l];
}
}
// Will add a for loop to combine the variables into string
$param = "$mArr1,$mArr0";
// send the string to array_multisort to be sorted by name
// have tried the following options:
// 1. array_multisort(explode(",",$param));
// 2. call_user_func_array(array_multisort,explode(",",$param));
// both do not sort & give me an error.
Thank you in advance for your help. I am open to any suggestions on other ways this can be accomplished, but I would like it to be in the php code if at all possible.
Just pass the array itself into the function.
arraySort($array);
Sort the array before splitting it in to other arrays using a custom sorting function:
$arr2[0] = "100::HOMEDEPOT";
$arr2[1] = "200::WALMART";
$arr2[2] = "300::COSTCO";
$arr2[3] = "400::WALGREENS";
$arr2[4] = "500::TACO BELL";
//Split the input in place, you could also use a new array for this
for($i = 0;$i < count($arr2);$i++)
{
$arr2[$i] = explode("::",$arr2[$i]);
}
//Define our new sorting function
function sort_second_item($a,$b)
{
return strcmp($a[1],$b[1]);
}
var_dump($arr2);
usort($arr2,'sort_second_item');
var_dump($arr2);
$rotated = array();
//Rotate $arr2
for($i = 0; $i < count($arr2); $i++)
{
for($j = 0;$j < count($arr2[$i]); $j++)
{
if(!isset($rotated[$j]))
{
$rotated[$j] = array();
}
$rotated[$j][$i] = $arr2[$i][$j];
}
}
var_dump($rotated);