1

When referring to an element inside a PHP string like an array, using square brackets [ ] you can use a number like [2] to select a specific character from the string. However, when using a string index like ["example"], it always returns the same result as [0].

<?php
$str="Hello world.";
echo $str; // Echos "Hello world." as expected.
echo $str[2]; // Echos "l" as expected.
echo $str["example"]; // Echos "H", not expected.

$arr=array();
$arr["key"]="Test."
echo $arr["key"]; // Echos "Test." as expected.
echo $arr["invalid"]; // Gives an "undefined index" error as expected.
echo $arr["key"];

Why does it return the same result as [0]?

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
Liam Hammett
  • 1,631
  • 14
  • 18
  • `$str["example"]` returns 0 from `$str = "Hello world."` which makes it return the first letter "H" –  Jun 29 '16 at 09:34
  • See here why: http://stackoverflow.com/questions/17193597/strings-as-arrays-in-php – mitkosoft Jun 29 '16 at 09:35
  • `$str["example"]` = `$str["0"] because of example` and hense h is recieved – Alive to die - Anant Jun 29 '16 at 09:36
  • 1
    Note that this produces a warning, which indicates it's not something you should ever be actually doing: https://3v4l.org/Dn4uR – deceze Jun 29 '16 at 09:38
  • Thanks for the explanations, I think my main problem here was that I just forgot typecasting a string to an integer results in 0 if no valid number is found. – Liam Hammett Jun 29 '16 at 15:41

1 Answers1

7

PHP uses type juggling to convert variables of a non fitting type to a fitting one. In your case, PHP expects your index to be a numeric, an integer to be exact. If you give it a string, it will try to parse it as a number. If not possible, it defaults to zero.

Sidenote: If you give it a string like "9penguins", you will get a 9.

PHP Manual on type juggling: http://php.net/manual/de/language.types.type-juggling.php

Joshua
  • 2,932
  • 2
  • 24
  • 40
  • 2
    Nitpick: It's *always* "possible" to cast a string to a number. The result may simply be `0` if no other useful number was found in the string. → http://php.net/manual/en/language.types.string.php#language.types.string.conversion – deceze Jun 29 '16 at 09:42