LoginSignup
4

More than 3 years have passed since last update.

【PHP】【エラー】Notice: Array to string conversion in~

Last updated at Posted at 2020-09-28

PHPについて学習内容を備忘録としてまとめます。
実装中に起きたエラーについて解決法まで記載します。

下記のようなマイページでユーザーの投稿数を表示させる際にエラーが発生しました。
image.png

起きた問題

ユーザーの投稿数を取得し表示したら下記のようなエラーが発生しました。

Notice: Array to string conversion in C:\xampp3\htdocs\user\user_mypage.php on line 22
Array

投稿数を表示させる箇所にArrayと表示されおり、投稿数は表示されていませんでした。
該当のコードはこちらになります。

<?php
print'<p>投稿数:'.get_user_count('post',$current_user['id']).'</p>';
?>

get_user_countは引数の値によって投稿数を取得しています。

原因

Array to string conversionとは配列が文字列に変換されてしまうというエラーメッセージです。
なので今回の場合はget_user_countで取得した配列が文字列に変換されているためにエラーが発生したと思われます。

解決法

配列の中の要素を返すようにすれば良いので、currentを使用します。
currentは配列の現在参照している要素を返します。

<?php
$a[] = 1;
$a[] = 2;
$a[] = 3;
print current( $a ); // 結果:1
?>

currentを先ほどのコードに追記してみます。

<?php
print'<p>投稿数:'.current(get_user_count('post',$current_user['id'])).'</p>';
?>

正常に動きました。
image.png

参考URL

https://php-beginner.com/function/array/current.html
https://marycore.jp/prog/php/notice-array-to-string-conversion/

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4