JavaScriptとPHPのifの違いサンプル

実際にJavaScriptおよびPHPで結果を出力しています。

const r1 = document.getElementById('resultJS1')
const r2 = document.getElementById('resultJS2')
const r3 = document.getElementById('resultJS3')

if ('0') {
  r1.textContent = true
} else {
  r1.textContent = false
}

if (Array()) {
  r2.textContent = true
} else {
  r2.textContent = false
}

// Array() と [] は同じ結果になる
if ([]) {
  r3.textContent = true
} else {
  r3.textContent = false
}

if ('0'):

if (Array()):

if ([]):

if ('0') {
  echo "<p>if ('0'): true</p>";
} else {
  echo "<p>if ('0'): false</p>";
}

if (array()) {
  echo "<p>if (array()): true</p>";
} else {
  echo "<p>if (array()): false</p>";
}

// array() と [] は同じ結果になる
if ([]) {
  echo "<p>if ([]): true</p>";
} else {
  echo "<p>if ([]): false</p>";
}

if ('0'): false

if (array()): false

if ([]): false

元記事を表示する