Seven
Seven

Reputation: 562

PHP - Is there a way to convert an array inside a string to a valid array in PHP?

I am having a simple problem that I think I need help with.

So, I have an <input type="hidden" name="valid_time[]" value="<?php print_r($valid_time); ?>"> tag.

Here, the value of that input is

Array ( [Monday] => Array ( [start_time] => 10:00:00 [end_time] => 17:00:00 ) [Tuesday] => Array ( [start_time] => 10:00:00 [end_time] => 17:00:00 ) [Wednesday] => Array ( [start_time] => 10:00:00 [end_time] => 17:00:00 ) [Thursday] => Array ( [start_time] => 10:00:00 [end_time] => 17:00:00 ) )

Now, when I submit the form and get the value of that input, I get the result of a string.

print_r($_POST['valid_time'][0]) => this gives me the value but in a form of a string.

I need the [0] because the supposed array is inside the $_POST['valid_time'] which is also an array.

print_r(gettype($_POST['valid_time'][0])); gives me string.

What I want is to have that as an array so that I can loop through it. Is there a way in PHP to do that?

PS: If this post is duplicated, pls drop the link and I'll give it a go. Thanks in advance!

Upvotes: 1

Views: 68

Answers (1)

Seven
Seven

Reputation: 562

So, I figured it out.

As for the value inside the input, it should be

<?php echo htmlspecialchars(json_encode($array)) ?>

Now, after POST-ing, you can retrieve it by using:

json_decode($_POST['array'])

So, basically, I just forgot to put the htmlspecialchars() function.

Upvotes: 1

Related Questions