1
$tally['zero']['status']='hello';
echo $tally['zero']['status'];
//prints hello, this is expected

In this example, why is only the first letter being printed?

$tally = array( "zero" => '0');     
$tally['zero']['status']='hello';
echo $tally['zero']['status'];   
// prints h, I was expecting hello

In this example, why is an error being thrown?

$tally['zero'] = 0;
$tally['zero']['status']='hello';
echo $tally['zero']['status'];
//prints Warning: Cannot use a scalar value as an array

2 Answers 2

3

In this example, why is only the first letter being printed?

$tally = array( "zero" => '0');
$tally['zero']['status'] = 'hello';
echo $tally['zero']['status']; // h

In PHP, strings can be indexed like arrays, and can also be modified in place. So 'status' becomes 0 when indexing the string, and the first character of hello is assigned to the first letter of $tally['zero']. For example, this:

$tally = array( "zero" => '01');
$tally['zero']['status'] = 'hello';
echo $tally['zero'];

Would print "h1".


In this example, why is an error being thrown?

$tally['zero'] = 0;
$tally['zero']['status'] = 'hello';
echo $tally['zero']['status'];

Like the error says, 0 is not an array. You can't index it, hence the warning.

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

2 Comments

Non-integer indexes for strings was removed as of PHP 5.4: php.net/manual/en/migration54.incompatible.php
PHP 5.4 would throw an E_WARNING in the situation you described, guiding the dev closer to the problem.
0

be careful about using " and '. While using " content can be interpreted as a varaible value.

0 != '0'   number/string

I think that all mystery is hidden here.

2 Comments

No. In PHP, 0 == '0'. For exact type checks, one must use !== or ===. That is not the origin of the question.
Means not equal. It's not php code. Will you explain me its not possible divide number by string too? Compare first rows of example 2 a 3.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.