Accessing variables, named with variables PHP - php

I am very new to programming and I got a job from school to do a "forecast" weather map from random generated numbers.
I already got 7 different arrays for every day (day1 -> day7) and all the code afterwards to check the required stuff and create the weather map.
Now I have the problem that I'd like to go through all the 7 arrays in 1 for-loop. I asked a friend and I think it's a very tiny thing missing / done wrong...
As I already got all the code afterwards (currently hardcoded for 1 day) I'd be pleased if you could provide me a solution for my (I guess crappy) way, not a totally different way eventhough it's most likely much more efficent what so ever.
I tried it like this:
for($daynr = 1; $daynr < 8; $daynr++){
$dayZ = 'day'.$daynr;
print_r($$dayZ);
...
This works like a charm and gives out array 1-7. But when I try to access a part of dayZ I get stuck:
echo $$dayZ[0][0]
Gives out:
Notice: Undefined variable: in C:\xampp\htdocs\index.php
on line 139
As many stuff later like $temp = explode('/',$$dayZ[$region_nr][3])... need to access the day-array it would be cool to have a solution for that.
Btw, something like echo $day1[0][0] works without problems.
Any help very appreciated, thanks in advance
Best regards
Michael

A cleaner solution would be to place the days in another array. So instead of $day1, $day2 etc you have an array $days containing your arrays for each day.
$days[0][0][0] // monday
$days[1][0][0] // tuesday
// ...

Use
${$dayZ}[0][0]
Keep in mind that this kind of variable format does NOT improve readability or good code.

Related

don't know why but somehow substr() doesn't work in code??(php)

recently I'm developing project via PHP, and today I faced a ridiculous situation, and couldn't get the reason still. So here's my problem
let's suppose that I have a string like this : 'myid(myname)'
what I wanted to get was myid and myname separately, so first I tried it with explode(), and I got result like below:
$order_identity= myid(myname);
$idexplode=explode("(", $order_identity);
$idexplode= Array ( [0] => myid [1] => myname) )
It was good, but not satisfied, because I still have ')' after 'myname' so to get rid of ')'
I used substr() which is very basic built-in php method to slice string value.
$order_name = substr($idexplode[1],0,-1);
and I thought I've done quite good and logged it,However, contrary to my expectations.
I still got 'myname)' when I echoed "echo $order_name"; !!!
I never met problem like this before and do not know why this happened to me :/.
can you tell me what's going on here and how to solve my problem?
thx for reading, your help will be appreciated.
p.s I already checked type and it was string! and also I checked if my php sever being lagged but it wasn't!!
use this $order_name - rtrim($idexplode[1],')') Instead of substr()....you get what your want.....hope you got the answer....

PHP - generic variable variable name of a variable

I am quite new on php and I got stuck with a problem..
I have an array with the day of the week call
$days = array( 'monday', 'tuesday', 'wednesday', 'thurday', 'frieday', 'sunday', 'saturday' );
also got a for loop index i=0 i<7 i++ that go along all day of the week so I dont need to repeat the code 7 times (1 for each day)
and I got open, close, hours and lots of info about each day..
so i some part I loop I need to asing a value to a generic variable called:
$ini_XXXXX_close where XXX is the day of the week so it's ($ini_$dias[$i]_close) generally speaking
when I tried to do: $ini_$dias[$i]_close=0; I got error...
So what I did is use a third variable..
$indexcloseini="ini_$dias[$i]_close";
and then
$$indexcloseini=0 which sucessfull generate the variable $ini_XXXXX_close=0;
( doble $$ read it from php manual)
But the problem is when I tried later to compare that variable with any other value inside and IF sentence..
The only way to acomplish is already to use an intermediate variable..
Is there any other easy way to do this.. I read php reference manual and tried using {!} and lots of thing but cant get it work..
Is there any function to transform this "$ini_$dias[$i]_close" to string so I could then make
$*STRING CONVERSION FUNCTION of $ini_$dias[$i]_close*
to create the variable composed by many variable values ?
Personally I would not go that route. It is complex, confusing and hardly ever a usefull solution. HJave you considered using a nested array for storing the values? Or even creating an object?
As an array, you could have:
$ini = array('monday'=>array(), 'tuesday'=>array(), //etc);
$ini[$day]['closeStatus'] = 0;

Undefined offset Error with array of exploded strings

I'm having some trouble with what is probably a very simple problem, but I just can't get my head around what the issue is.
I used fopen() to load a csv file, and broke it down into its different rows, loading the strings into an array of strings. I am trying to break apart each string to plug the values into a sql database.
$datalength is the number of lines there are in my csv file. The first line are the headings of the columns, so $x begins at 1.
for ($x=1;$x<$datalength;$x++)
{
$broken = explode(",",$lines[$x]);
$field1 = $broken[0];
$field2 = $broken[1];
$field3 = $broken[2];
$field4 = $broken[3];
echo $division;
$importdata = "INSERT INTO Teams (Field1,Field2,Field3,Field4)
Values ($field1,$field2,$field3,$field4)";
}
I keep getting the following error (BTW, I'm using WAMP):
Notice: Undefined offset: 1 in C:\wamp\www\test 2 (html-index)\upload_file.php on line 45, 46, 47
Lines 45-47 coincide with the $field2, $field3, and $field4 allocations of $broken[1] through $broken[3]. I don't understand why that is.
Anything I'm missing right off the bat? Any suggestions you think might make my life much easier would be warmly appreciated.
Anything I'm missing right off the bat?
Yes.
Something quite essential.
You are a virtual programmer. Your program deals not with the real data but with imaginary one. You imagine that some string you have can be exploded and put into array. While it is not. But, for some reason, you remain in a virtual world of your imagination and make no attempt to get in touch with a real one.
You are assuming that $lines[$x] contains a comma delimited string. Did you verify it?
You are assuming that $broken contains an array of four elements. Did you verify it?
Just by printing them out. This is so easy yet it will bring you into the real world at once - you will see the real data you process, not imaginary one. And be able to take any appropriate measures.
var_dump() is a best programmer's friend. Please make friends with this indispensable function too.
var_dump($lines[$x],$broken);
will clearly tell you, what's wrong with your offsets.

PHP accessing object stored in an array

I am new to taking an object oriented approach with php...actually I have a lot of learning to do overall, but the only way to learn is by doing.
So I have an array that holds several DateTime objects..I know this to be true because I have ran var_dump on the array and it indeed is holding several objects.
I need to go through each date and make sure there is never a difference greater than one day.
My research would seem to indicate that we cannot access or modify an object using the subscript operator:
$foo = $neat_array[$i+1]->format('U') ; //looking to format DateTime object as unix
//this returns an error every time
Okay I am fine with that, but I simply cannot figure out the syntax to access a specific item in the array so that it is seen as an object and does not pull an error.
I have pieced together that using -> is how I need to do it, but I never get any useable result.
Here is pseudo code of what I am trying to do
foreach($date_array as $date)
{
//check to see if the difference between the next date in the array and the current date of the array is greater than one day.
//I cannot use diff because I am on php 5.2 so I am trying this
$date->format('U') and then doing the math
}
Since learning by experimenting (and failing) is IMO a great way to learn, here is something to get you started.
$date_array = array(
new DateTime("tomorrow"),
new DateTime("now"),
new DateTime("yesterday"),
new DateTime("last day of october")
);
for( $i = 0, $count = count( $date_array); $i < $count; $i += 2) {
// Get the current object AND the next one in the array
echo $date_array[ $i ]->format('U'); echo '<br />';
echo $date_array[ $i + 1 ]->format('U'); echo '<br />';
// Now that you have the UNIX timestamps, you can do the math you need in here.
}
Note that the above will fail if the array contains an odd number of elements - I'll leave that fix up to you (if you need it).
Demo
Edit: You're probably getting that error for one of two reasons:
You're referencing an element that either isn't a DateTime object
You're referencing an element that doesn't exist in the date array
Here is a demo that shows error #2.
Edit: Here is a working example based off your answer that works for even and odd array sizes. It is essentially the same, except I don't bother with saving the values to variables or subtracting and comparing to 1 (since it's unnecessary).
$session_dates = $date_array = array(
new DateTime("tomorrow"),
new DateTime("yesterday"),
new DateTime("now"),
);
for( $i = 0, $count = count( $date_array) - 1; $i < $count; $i++)
{
if( ($date_array[ $i + 1 ]->format('U') - $date_array[ $i ]->format('U')) > 86400)
{
die( 'The date array does not contain consecutive dates.');
}
}
See it in action.
Okay..first of all, I appreciate everyone's help. Nickb, thanks for the help and the demos. As I surmised earlier, your suggestion that I might be trying to access an element that doesn't exist in the array was absolutely the case. What I am trying to do here is a pretty important part of a site I am creating..this whole mess will serve as a function in a class that checks reservation dates.
This is my first shot at Stack Overflow, so forgive me but I probably should have put more information in my initial question, but I was convinced I knew why the code wasn't working..which was completely incorrect!
See, since I always needed to know the current element, plus the next element in the array, my code was always breaking on the very last run of the loop, because it was trying to access the current key, plus the next one (which didn't exist on the last try).
Now, the real frustrating part is I screwed around with the for loop for this code all night and I still could not get it to cleanly go through every item without breaking...I would always over-run on that last item of the array and pull the error. I think the problem all along was that I never needed to go through every item in the array, just up to the second to last item (plus check the next one) then quit the loop.
Here is my code that finally works, but I don't really like it...I have a feeling there are some simple fixes in syntax and other areas that will make this more efficient...if not, the so be it...this is by the way, basically my testing code full of echos to see what was actually happening, but it is finally doing everything right:
$count = (count($session_dates)-1);
//never could get that last item to not trigger error, so subtracting one from the count was the only thing to end my frustration!!!but as I write this answer I think I see why and that is because we don't need to go through each item of the array, just each but the last item
echo '<p>'.$count.' this is the count of session dates </p>';
for ($i=0; $i<$count; $i++){
$unix_one = $session_dates[$i+1]->format('U');
//make some variables that are in the date format I want to visualize for echoing
$unix_echo_one = $session_dates[$i+1]->format("n".'/'."j".'/'."Y");
$unix_two = $session_dates[$i]->format('U');
$unix_echo_two = $session_dates[$i]->format("n".'/'."j".'/'."Y");
//see if the difference is greater than one day
if(($unix_one-$unix_two)/86400>1){
echo 'these dates are absolutely not consecutive, you fail!!';
//we only need one occurrence to wreck what we are trying to do, so just exit if it happens.
exit();
}
//I needed to see if any of the loop was happening to help try and figure this out!!
echo '<p>'.$unix_echo_one.'||'.$i.'||'.$unix_echo_two.'</p>';
}

Weekly shuffle of array

I have a set of 4 HTML list items and I'd like to shuffle the order they appear in once a week. I was wondering if anyone out there had a nice, elegant solution to this?
As always, I'd be enormously grateful for any input you might have!
UPDATE:
Unfortunately, even with the necessary .htaccess overrides, I just can't get any srand() based solutions to work on this particular server sadly, but have the following which could be used instead - at the moment, it only returns one list item - how could I modify it to show the four required? Once again, any ideas would be gratefully received :)
function RandomList($TimeBase, $QuotesArray){
$TimeBase = intval($TimeBase);
$ItemCount = count($QuotesArray);
$RandomIndexPos = ($TimeBase % $ItemCount);
return $QuotesArray[$RandomIndexPos];
}
$WeekOfTheYear = date('W');
$RandomItems = array(
"<li>North</li>","<li>South</li>","<li>West</li>","<li>East</li>");
print RandomList($WeekOfTheYear, $RandomItems);
Here is a simple and - I guess - pretty elegant solution, which does not involve storing values in a database, setting up cronjobs and other boring stuff of the like.
Let's pretend you have your list elements in $array:
srand(date('W'));
shuffle($array);
srand();
Now your array is shuffled, and will be shuffled the same way until next Monday.
This has a problem, though: it does not work with the Suhosin patch (installed by default in Debian). Still, now that you know about date('W') it will be easy to come up with an alternate solution yourself.
EDIT: if you don't want to implement your own pseudorandom number generator but you have Suhosin installed, you can put the following line in your .htaccess:
php_value suhosin.srand.ignore 0

Categories