2

I need to convert my array:

$tdata = array(11,3,8,12,5,1,9,13,5,7);

Into a string like this:

11-3-8-12-5-1-9-13-5-7

I was able to get it work with:

$i = 0;
$predata = $tdata[0];
foreach ($tdata as $value)
{
    $i++;
    if ($i == 10) {break;}
    $predata.='-'.$tdata[$i];

}

But was wondering if there is an easier way?

I tried something like:

$predata = $tdata[0];

foreach ($tdata as $value)
{
    if($value !== 0) {
        $predata.= '-'.$tdata[$value];
    }
}

but it result in bunch of Undefined Offset errors and incorrect $predata at the end.

So I want to learn once and for all:

  1. How to loop through the entire array starting from index 1 (while excluding index 0)?

  2. Is there a better approach to convert array into string in the fashion described above?

1 Answer 1

6

Yes there is a better approach to this task. Use implode():

$tdata = array(11,3,8,12,5,1,9,13,5,7);
echo implode('-', $tdata); // this glues all the elements with that particular string.

To answer question #1, You could use a loop and do this:

$tdata = array(11,3,8,12,5,1,9,13,5,7);
$out = '';
foreach ($tdata as $index => $value) { // $value is a copy of each element inside `$tdata`
// $index is that "key" paired to the value on that element
    if($index != 0) { // if index is zero, skip it
        $out .= $value . '-';
    }
}
// This will result into an extra hypen, you could right trim it

echo rtrim($out, '-');
Sign up to request clarification or add additional context in comments.

3 Comments

What???? So simple???? I was going crazy with those loops when there was a one string solution all along... THANK YOU!
@Acidon yes there is a built in function in PHP that already does this :) . Glad i was able to help
ahh, thanks for the answer for 1st question as well, you are the man! Using trim is brilliant and would work for my case as well :) God, I love PHP!

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.