So as the question states, im trying to create an array using a for loop, this seems as though its a simple question, but i cant find the asnwer on SO or googling. Heres what im doing:
$twelve=array("user","day");
for($i=0; $i<$value; $i++)
{
$total=$anarray[$i][value]; //get a value
$twelve[$i]=($i,$total); //insert values into array
}
this doesn't work, how should i go about getting this to work?
You may end up in a never-ending loop if $total=$anarray[$i][value]; is an increasing value. Regardless of the loop, you'll want to do as the other answerer mentioned, namely:
$twelve[$i] = array($i, $total);
I think it should be $twelve[$i] = array($i, $total);
Also, on this line;
$total=$anarray[$i][value]; //get a value
Unless value is defined as a constant, I think you want to do $anarray[$i][$value];.
PHP might not recognize value as a set variable or a constant, therefore crashes and never sets $twelve to any value.
I have found a solution that does work
in each loop simply do:
$twelve[$i]["user"]=$i;
$twelve[$i]["day"]=$total;
It would be nice if there is a way to do that in one line, but that is working.
Related
I've recently "inherited" a PHP web app that uses a mySQL database as part of its backend. While going through the code, I came across a block that absolutely puzzled me.
$results = array();
$results[] = $mysqli_result->fetch_array();
$results = $results[0];
return $results;
So I get that the first two lines are initializing an empty array and assigning the first row of results from a previous query to that new array. But the third line doesn't make sense to me. As I understand it, fetch_array() only grabs one row at a time; I can't think of any reason to have the $results = $results[0]; line. The best I can come up with is that it's leftover code from when mysql_result was removed.
Is there any reason to have this third line?
No, there is no reason. This is just an example of a "cargo cult code". When you don't know how to do something properly, you just copy/paste some existing code without real understanding whether it is necessary or not.
Of course it makes no sense to create an array, then create a new element in this array, and then reassign this array variable with the first element. Instead, just assign a variable:
$result = $mysqli_result->fetch_array();
Or - better - since this variable is returned right after the assignment, simply return it right away, as the $result variable isn't going to be used anywhere else.
return $mysqli_result->fetch_array();
I have multiple variables named day1Name, day2Name, day3Name, and so on. I also have exercise_11_Name, exercise_12_name, etc.
I have a lot of those, and the value I want to save in those variables depends on user input.
I don't want to have to write $variableName = $_POST['name'] for every single one because it's a lot and a terrible practice. Therefore, I want to use a for loop so my code looks cleaner.
What I am trying to accomplish is something similar to this I believe:
for(i=0, i<10; i++)
{
$day[i+1]name = $_POST['day[i+1]name'];
$exercise_1[i+1]_name = $_POST['excName1[i]'];
}
I know the way I wrote it is not going to work though.
P.S. Where I wrote [i+1] is where I just need the number, for example, $day[i+1]name should become the variable $day1name when i=0. Where I wrote [i], for example excName1[i], that's an array in which I want to retrieve the value of that specific index.
I would really appreciate some help in this.
Thanks! =]
create an array named $day_name, and name your form fields day_name_1, day_name_2 etc
then in your loop:
$day_name[$i+1] = $_POST['day_name_' . ($i + 1)]
do the same with the exercise variables.
I assume it is php, so your loop variable has to be $i, not i
The solution you are asking for is called somewhat variable variable or variable expansion and goes on like this:
for($i=0; $i<10; $i++)
{
$d=$i+1;
${"day{$d}name"} = $_POST["day{$d}name"];
${"exercise_1{$d}_name"} = $_POST["excName1{$i}"];
}
However I encourage you to look at "array" which is somehow what #Bart suggested above, which is probably a better way of organizing your data around.
I'm trying to look through an array of records (staff members), in this loop, I call a function which returns another array of records (appointments for each staff member).
foreach($staffmembers as $staffmember)
{
$staffmember['appointments'] = get_staffmember_appointments_for_day($staffmember);
// print_r($staffmember['appointments'] works fine
}
This is working OK, however, later on in the script, I need to loop through the records again, this time making use of the appointment arrays, however they are unavailable.
foreach ($staffmembers as $staffmember)
{
//do some other stuff
//print_r($staffmember['appointments'] no longer does anything
}
Normally, I would perform the function from the first loop, within the second, however this loop is already nested within two others, which would cause the same sql query to be run 168 times.
Can anyone suggest a workaround?
Any advice would be greatly appreciated.
Thanks
foreach iterates over a copy of the array. If you want to change the value, you need to reference it:
foreach($staffmembers as &$staffmember) // <-- note the &
{
$staffmember['appointments'] = get_staffmember_appointments_for_day($staffmember);
// print_r($staffmember['appointments'] works fine
}
From the documentation:
Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.
and
As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.
I have any array
$num_list = array(42=>'0',44=>'0',46=>'0',48=>'0',50=>'0',52=>'0',54=>'0',56=>'0',58=>'0',60=>'0');
and I want to change specific values as I go through a loop
while(list($pq, $oin) = mysql_fetch_row($result2)) {
$num_list[$oin] = $pq;
}
So I want to change like 58 to 403 rather then 0.
However I always end up getting just the last change and non of the earlier ones. So it always ends up being something like
0,0,0,0,0,0,0,0,0,403
rather then
14,19,0,24,603,249,0,0,0,403
How can I do this so it doesn't overwrite it?
Thanks
Well, you explicititly coded that each entry should be replaced with the values from the database (even with "0").
You could replace the values on non-zero-values only:
while(list($pq, $oin) = mysql_fetch_row($result2)) {
if ($pq !== "0") $num_list[$oin] = $pq;
}
I don't get you more clear, i thought your asking this only. Check this
while(list($pq, $oin) = mysql_fetch_row($result2)) {
if($oin==58) {
$num_list[$oin] = $pq;
}
}
In my simulated tests (although You are very scarce with information), Your code works well and produces the result that You want. Check the second query parameter, that You put into array - namely $pg, thats what You should get there 0,0,0,0,0...403 OR Other thing might be that Your $oin numbers are not present in $num_list keys.
I tested Your code with mysqli driver though, but resource extraction fetch_row is the same.
Bear in mind one more thing - if Your query record number is bigger than $numlist array, and $oin numbers are not unique, Your $numlist may be easily overwritten by the folowing data, also $numlist may get a lot more additional unwanted elements.
Always try to provide the wider context of Your problem, there could be many ways to solve that and help would arrive sooner.
My php reads in xml and I want to ouput the values within a given range. I have no way of knowing the size of the array or the range. However, I do know where to start; I have a $key that holds my current location. I also know where to stop; I have the word "ENDEVENTS" between each set. I want to get the values from my current position ($key) to my end position ("ENDEVENTS").
for example i may have an array set like this:
Array(
[0]=1
[1]=apple
[2]=straw
[3]=bike
[4]=ENDEVENTS
[5]=15
[6]=hair
[7]=shirt
[8]=nose
[9]=kiwi
[10]=ENDEVENTS
)
My code knows when I'm on 15 (in this example $key=5). I want to print 6 through 9. I tried using foreach but it's thats causing issues with what I'm trying to produce.
Any ideas?
Not so sure if i understood all ok but, ill give a try :-D
while(array[$key]!="ENDEVENTS"){
echo array[$key];
$key++;
}
Not entirely sure if I understand your question, but maybe this is helpful:
$stuff_to_print = array_slice($my_array,$key,array_search('ENDEVENTS',$my_array));
This should return an array with key values from the $key to the next 'ENDEVENTS' value