4

I am trying to create a string of every hour in the week starting at 0. The string would be 167 characters long and consist of 0/1 for every character representing true/false for that hour.

I know you can edit strings as so :

$foo = "123456789";
echo $foo[0]; // outs 1
echo $foo[1]; //outs 2

$foo[0] = 1;
$foo[1] = 1;

echo $foo[0]; // outs 1
echo $foo[1]; // outs 1

So I assumed I could set a blank string and use the same method to 'build' it. So I am running a loop from 0-167 and while doing so checking if the 'hour' is in the $hours array. If it is I set it to 1 in my string... if not it is set to 0. Problems :

1. This does not work by setting $inputHours = '' and it just creates an array instead of the string I want.

2. Is there a more optimized manner to check if an hour is set other than using in_array 167 times?

//array of selected hours
$hours = array(1, 25, 34, 76, 43)

//create selected hours string from selection
$inputHours = '';

for ($x = 0; $x < 168; $x++) {
    $inputHours[$x] = in_array($x, $hours) ? 1 : 0; 
} 

Expected output would be $inputHours = '0011010101...' depending if set for a total lenth of 167 characters.

4
  • curious, what's the string going to be used for, keeping the select hours array seems more efficient Commented May 18, 2014 at 22:36
  • I have been trying to think of a good way to store selected hours for an entire week in sql for rows. I originally had 7 rows of 24... one for each day, but queries were taking longer than I wanted because I had to join those rows for each 'result' if I wanted to display an entire weeks schedule for each. I thought of this method today. Easy inserts, easy queries, one row per instead of 7, and reading values is as easy as $week[hour#] Commented May 18, 2014 at 22:43
  • bad idea, create hours table Commented May 18, 2014 at 22:47
  • Explain your thoughts and reasoning - this is MUCH quicker and easier than having 168 columns OR 7 rows of 24 columns in the database. I also have no need for query'ing specific hours only the set as a whole. Commented May 18, 2014 at 23:03

1 Answer 1

11

You can concatenate characters in one string with .= operator and check condition using ternary operator ([expression] ? [true] : [false]) with in_array() function:

for($x = 0; $x < 168; $x++)
    $inputHours .= in_array($x, $hours) ? 1 : 0;

Example

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.