Skip to content

Instantly share code, notes, and snippets.

@ericlbarnes
Created July 29, 2012 03:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ericlbarnes/3195974 to your computer and use it in GitHub Desktop.
Save ericlbarnes/3195974 to your computer and use it in GitHub Desktop.
Stringify Attributes
/**
* Stringify attributes for use in html tags.
*
* Helper function used to convert an array or object of
* attributes to a string
*
* @param mixed
* @return string
*/
function _stringify_attributes($attributes, $js = FALSE)
{
if (is_object($attributes) && count($attributes) > 0)
{
$attributes = (array) $attributes;
}
if (is_array($attributes))
{
$atts = '';
if (count($attributes) === 0)
{
return $atts;
}
foreach ($attributes as $key => $val)
{
if ($js)
{
$atts .= $key.'='.$val.',';
}
else
{
$atts .= ' '.$key.'="'.$val.'"';
}
}
return rtrim($atts, ',');
}
elseif (is_string($attributes) && strlen($attributes) > 0)
{
return ' '.$attributes;
}
return $attributes;
}
public function test_stringify_attributes()
{
$this->assertEquals(' class="foo" id="bar"', _stringify_attributes(array('class' => 'foo', 'id' => 'bar')));
$atts = new Stdclass;
$atts->class = 'foo';
$atts->id = 'bar';
$this->assertEquals(' class="foo" id="bar"', _stringify_attributes($atts));
$this->assertEquals(' class="foo" id="bar"', _stringify_attributes('class="foo" id="bar"'));
}
public function test_stringify_js_attributes()
{
$this->assertEquals('width=800,height=600', _stringify_attributes(array('width' => '800', 'height' => '600'), TRUE));
$atts = new Stdclass;
$atts->width = 800;
$atts->height = 600;
$this->assertEquals('width=800,height=600', _stringify_attributes($atts, TRUE));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment