Jump to content

array unshift fails


TheFilmGod

Recommended Posts

	<?php			// Unserialize data as needed and add reply comment

				// Put new comment data into array for latter adding
				$data = array($gender, $name, $message);

				// If previous reply comments already existed
				if ($reply_comments != NULL) {

					// Unserialize data
					$comments = unserialize($reply_comments);
					print_r($comments);
					echo "<p>";

					// If 5 comments are already present in this array, remove last one
					if (count($commments) == 5) {
						$comments = array_pop($comments);
					}

					// Add new reply comment as the first element in the array
					$comments = array_unshift($comments, $data));
				}
				// Else no previous reply comments
				else {

					// Create new array with posted reply comment data
					$comments = array($data);
				}

			// Serialize data so it can be updated back into mysql
			$comments_db = serialize($comments);

			print_r($comments);?>

 

Problem ->

 

If not null and data is unserialized -> works correctly

 

First print_r() gets the expected results of:

 

Array ( [0] => Array ( [0] => male [1] => greeeeeeee [2] => greeeeee ) )

 

Skips the next part because array isn't equal to 5 elements.

 

Then it fails. the array_unshift($comments, $data)) doesn't work as it outputs this data:

 

2

 

Just "2". WTF?

 

Link to comment
https://forums.phpfreaks.com/topic/171590-array-unshift-fails/
Share on other sites

if you are trying to unshift the array then  array unshift($comments, $data)); that will add the data to the top of the array. it does not need the  $comments =

 

You do need $comments because you are telling php to unshift the $comments array and add $data -> as an element in the beginning.

 

I got it to work.

 

array_unshift($comments, $data);

was the solution

Link to comment
https://forums.phpfreaks.com/topic/171590-array-unshift-fails/#findComment-904845
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.