LoginSignup
hazamashion
@hazamashion (shion hazama)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

【PHP掲示板作成】配列のはじめが正しく表示されず以下のエラーが出る。

解決したいこと

ひとこと掲示板を作成しています。

発生している問題・エラー

配列のはじめが正しく表示されず以下のエラーが出る。
Notice: Uninitialized string offset

スクリーンショット 2022-11-25 1.05.06.png

該当するソースコード

<?php
$errors[]='';
$lines[]='';
$date = date("Y年m月d日h時m分s秒");

define('FILE_PATH', './bbs.txt');

if($_SERVER['REQUEST_METHOD'] === 'POST'){
    //名前もコメントも両方とも入力されたら
    if(isset($_POST['name']) === true && isset($_POST['comment']) === true){
        $name = $_POST['name'];
        $comment = $_POST['comment'];
    }
    $fp = fopen(FILE_PATH, 'a');
    if($fp !== false){
        //カンマで区切ってCSVで読み込みたい
        $log = $name . ',' . $comment . ',' . $date . "\n";
        $result = fwrite($fp, $log);
    }
    fclose($fp);
}
if(is_readable(FILE_PATH) === true){
    $fp = fopen(FILE_PATH , 'r');
    if($fp !== false){
        $text = fgetcsv($fp);
        while($text !== false){
            $lines[] = $text;
            $text = fgetcsv($fp);
        }
    }
    fclose($fp);
}
?>
<!DOCTYPE html>
<html lamg="ja">
<head>
    <meta charset="UTF-8">
    <title>ひとこと掲示板</title>
    <style>
    .matrix {
        border-collapse: collapse;
    }
    .matrix th, td {
        border: solid 1px black;
        padding: 5px;
    }
    </style>
</head>
<body>
    <form method="POST">
        <p>名前</p>
        <label><input type="text" name="name"></label>
        <p>コメント</p>
        <label><input type="text" name="comment"></label>
        <input type="submit">
    </form>
    <table class="matrix">
        <thead>
            <th>名前</th>
            <th>コメント</th>
            <th>発言日時</th>
        </thead>
        <tbody>
            <?php foreach($lines as $line){ ?>
            <tr>
                <td><?php print htmlspecialchars($line[0], ENT_QUOTES, 'UTF-8'); ?></td>
                <td><?php print htmlspecialchars($line[1], ENT_QUOTES, 'UTF-8'); ?></td>
                <td><?php print htmlspecialchars($line[2], ENT_QUOTES, 'UTF-8'); ?></td>
            </tr>
            <?php } ?>
            
        </tbody>
    </table>
    <?php var_dump($lines);?>
</body>
</html>

テキストファイル"bbs.txt"

田中,おはよう,2022年11月25日12時11分42秒
安田,こんにちは,2022年11月25日12時11分43秒
森本,こんばんは,2022年11月25日12時11分54秒

自分で試したこと

ググってみたところ、主に配列やオブジェクトではなく文字列型の変数に対して存在しないキー名を指定した呼び出しをすると発生するエラーであることがわかったが、どこが間違っているのかがわからない

0

1Answer

初期化で

 $lines[]='';

としている時点で$linesに1行分の空行が追加されてしまっているからではないでしょうか。
空配列として初期化したいのであれば$lines = [];かと思います。

2

Comments

  1. @hazamashion

    Questioner
    無事表示されるようになりました!
    ありがとうございます!

Your answer might help someone💌