skip to Main Content

Hello my dear coding friends.
I have a time, formatted like this 08:00:00. That time comes from my phpMyAdmin database where i have a "time" field and i get that field by using a query in my php code. The variable type of that mysqli variable containing the time is string, so i want to cut the minutes and seconds part off and turn the rest into an integer by adding (int). The code looks like this: Image of code

if (strpos ($meetings["dtStartZeit"], "0") == 0) {
                            
    $startTimeString = substr ($meetings["dtStartZeit"], 1, 1);
                            
} else {
                        
    $startTimeString = substr ($meetings["dtStartZeit"], 0, 2);
                            
}
                        
$startTimeNumber = (int)$startTimeString;

Now comes the confusing part. If i have a string like this –> "8" and I want to turn it into an integer by using the above mentioned function, the result is 9 and not 8. The even more confusing part is that if I increase the value of that variable by 1, the result is 8.

Can someone explain me this please?

2

Answers


  1. To convert a string to an int you use intval()

    because a string is an object of chars casting them wont ever work as expected which is what (int) is doing

    Login or Signup to reply.
  2. You don’t need to use strpos or substr here. Use a single line type cast instead all of your code:

    $startTimeNumber = (int) $meetings['dtStartZeit']; // "08:00:00" --> 8 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search