Print One-dimensional array in input hidden

3

I have the variable $style = [1, 2, 1] ; in php and what I want is to send this Array as you see it here, in the value of a input hidden of HTML , to capture it in my controller and use it in other opreations.

What I need is that this input hidden carry in its value the Array as it is ( [1, 2, 1] ), because when I'm going to use it in my operations, only this format is the who receives and unfortunately all my attempts have been unsuccessful, because they print me in a different way, I would appreciate your help.

$style = [1, 2, 1];

<input type="hidden" name="style" id="style" value=<?php $style ?>
    
asked by Jhonatan Anderson Ospina Suare 27.07.2016 в 17:06
source

4 answers

0

Something you can try is to serialize the arrangement and send it through the hidden input

//Input desde el que se envía
$style=[1,2,1];
<input type='hidden' name='style' value="<?php echo htmlentities(serialize($style)); ?>" />

//Archivo donde se recibe
$passed_array = unserialize($_POST['style']);

Another option would be to use a session and call it from there

session_start();
$style=[1,2,1];
$_SESSION['style'] = $style;

One advantage of using a session is that the client can not see the data directly, seeing the html code displayed by the browser.

    
answered by 27.07.2016 в 17:17
0

I recommend using the Implode function that generates a string from the elements of the received array

<?php

$array = array('apellido', 'email', 'teléfono');
$string = implode(",", $array);

echo '['.$string.']'; // [apellido,email,teléfono]
?>

In this way, you send the chain to the controller and view it exactly as you need it.

    
answered by 27.07.2016 в 17:26
0

Perhaps the most "appropriate" way to pass an array is through a foreach with several fields, whose name is the same (an array with empty keys):

<?php
$style = [1, 2, 1];

foreach ($style as $value) { ?>

    <input type="hidden" name="style[]" value="<?php echo $value ?>">

<?php } ?>

The only "problem" here would be that you can not use the same id for the 3 fields, in case you need it for something in your frontend.

At the moment of receiving the form data, you simply take the variable $_POST["style"] and there you have it formatted as a normal array [1,2,1] .

If what you really want is to send the values as a string, then one solution is to use implode on the array you already created:

<?php
$style = [1, 2, 1];

$styleStr = implode(",", $style);
?>

<input type="hidden" name="style" id="style" value="[<?php echo $styleStr ?>]">
    
answered by 27.07.2016 в 17:23
0

Here's the solution:

link

<?php

$style = [1, 2, 1];
$arr = "";
$i = 0;

foreach ($style as $val) { 

    if ($i == 0) {
        $arr =  $val;
    } else {
        $arr = $arr . "," . $val;
    }

    $i++;

}

?>

<input type="hidden" name="style" id="style" value="<?php print([".$arr."]"); ?>"/>

Greetings ...

    
answered by 27.07.2016 в 21:04