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]?

5
  • $str["example"] returns 0 from $str = "Hello world." which makes it return the first letter "H" Commented Jun 29, 2016 at 9:34
  • See here why: stackoverflow.com/questions/17193597/strings-as-arrays-in-php Commented Jun 29, 2016 at 9:35
  • $str["example"] = $str["0"] because of example and hense h is recieved Commented Jun 29, 2016 at 9:36
  • 1
    Note that this produces a warning, which indicates it's not something you should ever be actually doing: 3v4l.org/Dn4uR Commented Jun 29, 2016 at 9: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. Commented Jun 29, 2016 at 15:41

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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. → php.net/manual/en/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.