Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Build a Basic PHP Website (2018) Listing and Sorting Inventory Items Sorting Array Items

Obayanju Damilare
Obayanju Damilare
3,383 Points

Why does $output change to a string

I changed this line of code :

$output[$id] = $sort; 

to

$output = $sort;

and I used

$output 

in the asort function instead of

$output[$id]

and then php tells me that asort parameter which is

 $output

is a string. But we have already defined

$output = array(); 

at the beginning of the array_category function, why then does php recognize it as a string when I use it in asort. Thanks for your answer in advance :)

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! The reason it changes from an array to a string is because the variable is now being entirely redefined and overwritten with a string. When you do $output = $sort; you are telling PHP to take the entirety of the array and replace it with that string that's contained in the $sort variable.

I made a little code snippet that I encourage you to run in workspaces which will show what's happening a little more clearly.

<?php
$testArr = array();
var_dump($testArr); // testArr is now an array

$testArr = "Hi there!";
var_dump($testArr);  //testArr is now a string

$testArr = array();  
var_dump($testArr);  //testArr is now an array

$testArr = 2.39093;
var_dump($testArr);  //testArr is now a float

?>

We start with an array. Then we replace the entirety of the array with a string. This is perfectly valid PHP, but probably not what we're intending. We probably wanted to replace an element inside the array with a string... not the entire array. So then we redeclare it as an empty array. This time we replace the entire array with a float. Once again, this is perfectly valid, but likely not what we're intending.

Hope this helps! :sparkles: