EDIT: The string was being outputted and interpreted by the browser. Silly mistake.
In my project, I have created a class to generate the HTML tags I need, rather echo them all out myself. I have a function called generateTag($control, $isCardValue = true)
in a php class called Card
. This function generates an HTML tag based on the properties passed through the array parameter $control
. Here is what the function looks like:
public function generateTag($control, $isCardValue = true) {
if ($isCardValue) {
// First we convert the 'class' element to an array
if (isset($control['class']) && gettype($control['class']) !== 'array') {
$control['class'] = array($control['class']);
}
// Then we add the 'card-value' class to that array.
$control['class'][] = 'card-value';
}
// The tag key is mandatory
$tag = '<' . $control['tag'];
// All keys other than 'tag' & 'content' are considered attributes for the HTML tag.
foreach ($control as $key => $value) {
switch ($key) {
case 'tag':
break;
case 'content':
break;
default:
if (gettype($value) === 'array') {
$tag .= ' ' . $key . '="' . implode(' ', $value) . '"';
} elseif (gettype($value) === 'NULL') {
$tag .= ' ' . $key;
} else {
$tag .= ' ' . $key . '="' . $value . '"';
}
break;
}
}
$tag .= '>';
// If the 'content' key is not passed through $control, we assume that the tag
// doesn't need to be closed (e.g. <input> doesn't need a closing tag)
if (isset($control['content'])) {
if (gettype($control['content']) === 'array') {
foreach ($control['content'] as $child) {
$tag .= $this->generateTag($child);
}
} else {
$tag .= $control['content'];
}
$tag .= '</' . $control['tag'] . '>';
}
return $tag;
}
I use this function to create all the <option>
tags for a <select>
box. I simply loop through an array to generate the tags:
foreach ($lists['tags'] as $key => $tag) {
$tag_options[$key] = array(
'tag' => 'option',
'value' => $tag['tag_id'],
'content' => $tag['tag_name_en'],
);
var_dump($card->generateTag($tag_options[$key], false));
}
This is where things get weird. I call a var_dump on the generated string and I get the following output:
string(32) "" string(35) "" string(33) "" string(33) "" string(38) "" string(32) "" string(42) "" string(30) "" string(41) "" string(34) "" string(35) "" string(34) "" string(29) "" string(36) "" string(37) "" string(31) "" string(36) "" string(67) "" string(36) "" string(33) "" string(36) "" string(36) ""
It appears that it's creating an empty string of length ~35? The weirdest thing is that when I call a substr($tag_options[$key], 0, 1)
, it gives me <
as it should. But when I call substr($tag_options[$key], 0, 2)
, it gives me the "empty" string of length 2. Any insight on what's going on?