0

Following is my code; i didnot get problem what's wrong with it;

$units=explode(";",$course->unitinfo);
foreach($units as $unit)
{
    $unitinfo=explode("|",$unit);
    echo'<tr>
            <td>'.$unitinfo[1].'</td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>';
}

Here string $course->unitinfo comes with two delimiters first is ; and contains info of one row and second delimiter is | pipe sign; first explode works fine; second explode generates error with undefined offset, if print it with print_r is shows-

Array
(
    [0] => 1
    [1] => Mechanics
    [2] => 5
    [3] => 1,2
    [4] => 3,1
)

and the problem is cant access via its index - $unitinfo[1]; where i am wrong

3
  • 1
    can you print $units array in question? Commented Dec 5, 2015 at 11:27
  • var_dump($unit, $unitinfo); Commented Dec 5, 2015 at 11:29
  • It does feel like unit is not an array. Commented Dec 5, 2015 at 11:56

1 Answer 1

1

You need to check for occurence of | to avoid 'undefined offset' warnings in your script:

$testString = 'test|1;test|2;test3';

$units=explode(";",$testString);
foreach($units as $unit)
{
    $value = '';
    if (strpos($unit, '|') !== false) {
        $unitinfo=explode("|",$unit);
        $value = $unitinfo[1];
    } else {
        $value='No pipe found';
    }


    echo'<tr>
            <td>'.$value.'</td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>';
}

Will show:

1 2 No pipe found
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.