0

i want want to parse html attribute with function. in my fnction implode do not work correctly and could not convert array to simple string.

for example my array Result is:

Array
(
    [0] => id='myLabel'
    [1] => class='myClass'
    [2] => style='width:100%;'
)

after imploding that i get this Result:

Array
(
    [0] => 0='id='myLabel' class='myClass' style='width:100%;''
)

Result must be:

Array
(
    [0] => "id='myLabel' class='myClass' style='width:100%;'"
)

My function :

    public function setAttribute( $attributs ){
        $html = [];
        foreach ( (array)$attributs as $key => $value) {
            $html[] = $key .'='. "'".$value."'";
        }
        return implode( $html, ' ');
    }
5
  • 1
    php.net/manual/de/function.serialize.php does the job Commented Apr 11, 2014 at 5:38
  • What is your expected output? Commented Apr 11, 2014 at 5:40
  • Actually $key holds array index value. That's y in your array preceding with 0 Commented Apr 11, 2014 at 5:43
  • Your tried seems to correct.You should not get 0 and weird quotes after implode. Commented Apr 11, 2014 at 5:45
  • Your code works fine. Please post how you are calling setAttribute. Commented Apr 11, 2014 at 5:47

1 Answer 1

1

Based on the manual, it is used this way:
string implode ( string $glue , array $pieces ) $string = ('<space>', $array)

On your code its the other way around:
return implode( $html, ' ');

Sample code:

$array = array(
    "id='myLabel'",
    "class='myClass'",
    "style='width:100%;'",
);

Output:
Array
(
    [0] => id='myLabel'
    [1] => class='myClass'
    [2] => style='width:100%;'
)

$result[0] = implode(' ', $array);
Output:
Array
(
    [0] => id='myLabel' class='myClass' style='width:100%;'
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.