1

I'm confused as to how PHP determines whether a variable is a string or an array. It seems to depend on the operators being used.

Here's an example:

<?php
$z1 = "abc";
$out = "";
for ($i = 0; $i < strlen($z1); $i++)
{
    // $out[$i] = $z1[$i]; 
    $out = $out.$z1[$i];
}
print $out;
?>

In the above version $out becomes a string (print $z1 shows "abc"). However, if I use the first line $out[$i] = $z1[$i];, $out becomes an array.

Can someone please clarify why this happens, and if its possible to access a string's characters with square brackets without converting the output to an array?

2
  • Interestingly, if you initialise $out as a non-empty string, e.g. $out = 'a', it stays a string... Commented May 18, 2014 at 19:00
  • 1
    From the PHP Manual: String access and modification by character. As a more general note, the PHP Manual is quite good: you should take a look. Commented May 18, 2014 at 19:00

2 Answers 2

1

The definition of a string in PHP is considered a set of data writen in linear format (i.e: $var = "username=SmokeyBear05,B-day=01/01/1980";)

An array however is a set of data broken down into several parts. A sort of list format if you will. As an example I've written the data string from before, into an array format...

Array(['username']=>"SmokeyBear05", ['B-day']=>"01/01/1980")

Now strings are generally defined as such: $var="Your String"; Arrays however can be written in three different formats:

$var1 = array('data1','data2','data3');
$var2 = array('part A'=>'data1','part B'=>'data2','part C'=>'data3');

The output of var1 starts the index value at 0. The output of var2 however, sets a custom index value. Now the third way to write an array (least common format) is as such:

$var[0]="data1";
$var[1]="data2";
$var[2]="data3";

This takes more work, but allows you to set the index.

Most web developers working with PHP will set data from an external source as a string to deliver it to another PHP script, and then break it down into an array using the explode() function.

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

Comments

0

When you define variable $out = "", for loop doesn't understand this variable as string value. If you set $out[$i] value, by default, it was treated as an array.

If you want to get the output result as string value, you can define $out = "a" to make sure it's a string variable.

3 Comments

While this appears to be the answer, it'd be interesting why PHP doesn't treat the string "" as a string but does "a".
Thanks for replying. So how do I define an empty string?. Based on the replies here, writing $out="" will create an array.
@user51726 It doesn't seem to be possible in your case. If you hate the a string, try with a white space $out=' '.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.