1

I am still new to PHP.

My problem: Warning: array_push() expects parameter 1 to be array

Description: I have a list of room numbers that I am parsing. The first number of the room number refers to the floor of the room. I want to create a 2d array that holds floor numbers, and each floor consists of the rooms.

Code:

    $array = self::getAllRooms();
    $floorArray = array();
    foreach($array as $row)
    {
        $floorNum = substr($row['room_no'],0,1);
        if (in_array($floorNum, $floorArray))
        {
            array_push($floorArray[$floorNum], $row['room_no']);
        }
        else 
        {
            array_push($floorArray, $floorNum);
            array_push($floorArray[$floorNum], $row['room_no']);
        }
    }

How do I append the room numbers to the "1" category referring to floor 1?

Thanks a lot!

2 Answers 2

2

Code:

$array = array(array('Stack','Overflow'));

$array[0][] = '.com';
// or
array_push($array[0],'.com');

Output:

Array
(
    [0] => Array
        (
            [0] => Stack
            [1] => Overflow
            [2] => .com
            [3] => .com
        )

)
0

You have a bug here:

array_push($floorArray, $floorNum);
array_push($floorArray[$floorNum], $row['room_no']);

The first line pushes an element with a value of $floorNum into the array, but the second line expects an element with a key equal to $floorNum to be present.

You can do what you want much simpler:

foreach($array as $row)
{
    $floorNum = substr($row['room_no'],0,1);
    $floorArray[$floorNum][] = $row['room_no'];
}
2
  • Hi! After trying to print the contents of the arrays i get "Array" instead of the floor number. foreach($floorArray as $row1) { echo $row1."<br>"; foreach($row1 as $row2) { echo $row2; } } Commented Apr 25, 2011 at 0:53
  • @AeroChocolate: Don't print arrays with echo. Use print_r instead: echo '<pre>'; print_r($floorArray); echo '</pre>';. Commented Apr 25, 2011 at 8:24

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.