PHP8.x環境がレンタルサーバーなどで使えるようになってきましたね。
これまでもPHP5.xからPHP7.xにバージョンが上がった際など、今まで動いてきたソースコードでエラーが出る事例は多数ありました。
この度タイトルまんまですが「Warning: Undefined array key 0〜」が出て処理がうまくいかない局面に遭遇し、isset() 関数を使用して要素が存在するかを事前に確認してから処理をするというのをChat GPT教わった次第です。
<php?
//記事内の最初に出てくる画像素取得する
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){
$first_img = get_template_directory_uri() . '/images/img_noimages.jpg';
}
return $first_img;
}
?>上記のようなソースコードがあった場合PHP8.x環境では「$matches [1] [0]」の要素が存在しないという理由でエラーが出てしまいます。
そこで、isset() 関数で「$matches [1] [0]」が存在した場合に処理をするというように(Chat GPTが)書き換えました。
<?php
//記事内の最初に出てくる画像素取得する
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
if (isset($matches[1][0])) { //$matches[1][0]が存在するか判定
$first_img = $matches[1][0];
}
if (empty($first_img)) {
$first_img = get_template_directory_uri() . '/images/img_noimages.jpg';
}
return $first_img;
}
?>便利ですねChat GPT。
コメントを残す