Skip to content

Instantly share code, notes, and snippets.

@koji-k
Last active February 27, 2017 14:41
Show Gist options
  • Save koji-k/6552cf6c416ec66449723437ba2ab612 to your computer and use it in GitHub Desktop.
Save koji-k/6552cf6c416ec66449723437ba2ab612 to your computer and use it in GitHub Desktop.
<?php
class Introduce {
    private $arraylist = array();

    public function regist($num) {
        $this->arraylist[] = $num; 
    }

    public function show() {
        for ($i = 0; $i < count($this->arraylist); $i++) { 
            if ($i % 2 == 0) { 
                var_dump($this->arraylist[$i]);
            } else {
                echo "Does not show odd value";
            }
            echo "\r\n";
        }
    }
}


$obj = new Introduce();
$obj->regist(array("A", "aaa"));
$obj->regist(array("B", "bbb"));
$obj->regist(array("C", "ccc"));
$obj->regist(array("D", "ddd"));

$obj->show();
?>

実行結果:

root@6f7bd614daf3:/var/www/html# php test.php 
array(2) {
  [0]=>
  string(1) "A"
  [1]=>
  string(3) "aaa"
}

Does not show odd value
array(2) {
  [0]=>
  string(1) "C"
  [1]=>
  string(3) "ccc"
}

Does not show odd value
root@6f7bd614daf3:/var/www/html# 

@koji-k
Copy link
Author

koji-k commented Feb 27, 2017

メモ。元のソースではecho "$this->arraylist"となっていた部分をvar_dump($this->arraylist[$i]);に変更。
この変更によって、$this->arraylist$i番目のデータを表示する、という処理になる。
元のecho "$this->arraylist"だと、 $this->arraylistという配列自体 とう意味になるので、PHPの場合はechoで配列の値を表示できない。なのでエラーになっていた。
なお、$this->arraylistという配列には、さらに各要素に配列が格納されているので、多次元配列になる。
つまり、$this->arraylist[$i]で取得される値自体もまた配列なので、echoでは表示できない。そのため今回はvar_dumpを利用した。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment