I have an array in PHP that I am looping through to get content.
When echoed, the results of my array variable $myArray
looks like the below
Array(
[0] => ABC
[1] => DEF
[2] => GHI
[3] => JKL
)
Array(
[0] => MNO
[1] => 123A
[2] => 123B
[3] => 123C
)
Array(
[0] => orange
[1] => yellow
[2] => green
[3] => blue
)
But when i pass this to the html data element using
data-results = "$myArray"
I get a
Notice: Array to string conversion
error.
How can this be passed as one array to the html data element?
This has probably already been answered elsewhere, but you cannot echo an array out. You can only echo out a scalar value or an object that has a __toString()
method on it.
So it's data-results="{$myArray[0][0]}"
or something else in your case, since you have a multi-dimensional array. What you probably want is some sort of for loop:
foreach ($myArray as $arr) {
foreach ($arr as $value) {
echo "data-rule={$value}";
}
}
If you want to print your array into a string equivalent, you can use:
$stringArray = print_r($array, true);
echo $stringArray;
If you wish to print it as a JSON string, you can use:
$array = array('a', 'b', 'c');
echo json_encode($array);
I think , you may use the below code . It will work incase if array values having special characters .
<div data-results="<?php echo htmlspecialchars(json_encode($myArray), ENT_QUOTES, 'UTF-8'); ?>"></div>