0

My goal is to make ant assoc array from the values of for loop.

//$from_time value is 6 and $to_time value is 23

for ($i = $from_time; $i <= $to_time; $i++) {
        $working_time_array[] = $i;
    }
echo json_encode($working_time_array);

The output I get on AJAX success, and when I console.log it, I get result as such :

["6",7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]

Preferred result is

["6","7","8","9","10"]... etc

3 Answers 3

5

The only difference between the two results is one result set contains integers and the other contains strings. If you want those values to be strings just cast them when assigning them to the array:

for ($i = $from_time; $i <= $to_time; $i++) {
    $working_time_array[] = (string) $i;
}

This really shouldn't be necessary unless your client side is expecting strings only.

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

1 Comment

Yes that was the problem. I'm new to arrays so I will ask on more question. Now it's good, but is it possible to remove those values that are same in other array. As in this example $working_time_array[] result is ["6","7","8","9"].. My other $array[] result for example is ["6","7"]. How do I remove the values that are in $array from my $working_time_array[]?
0

You would need to cast $i to a string before pushing it to the array.

for ($i = $from_time; $i <= $to_time; $i++) {
        $working_time_array[] = (string)$i;
}

Comments

0

why would you convert int to string?

for your goal this should work

for ($i = $from_time; $i <= $to_time; $i++) {
    $working_time_array[] = "$i";
}
echo json_encode($working_time_array);

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.