Create string in one character at a time with loop

arrays, for-loop, loops, php, string

Solution

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

Problem

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.

Original source