array_unshift() with empty array
I want to add an element to the beginning of an array, but this array might be empty sometimes. I've tried using array_unshift()
but it doesn't seem to like empty arrays... should I simply check for the empty array and append the element manually, or does array_unshift()
not mind empty arrays but I'm just being a klutz?
Here is my code at the moment:
$sids = array(); $sids = explode(",", $sid['sids']); array_unshift($sids, 开发者_运维百科session_id());
The contents of the $sids
array are taken from a database and are comma separated values.
Thanks,
James
EDIT
I've managed to fix this now - sorry everyone!
Here's the updated code:
$sids = array(); if(!empty($row['sids'])) { $sids = explode(",", $row['sids']); } array_unshift($sids, session_id());
If $sid['sids'] is empty, explode will return FALSE Then $sids will be equal to FALSE and the subsequent call to array_unshift will fail.
You should probably make sure $sids is an array before calling array_unshift. Here's a way to do it:
if(!empty($sid['sids']))
$sids = explode(",", $sid['sids']);
else
$sids = array();
array_unshift($sids, session_id());
First off, your first line of code is pointless; explode always returns a value, whether it be an array or FALSE
. You're guaranteed to overwrite that value once you call explode.
Secondly, your code should work. One minor edit I'd make is this:
<?php
$sids = array();
$sids = explode(",", $sid['sids']);
if(is_array($sids))
array_unshift($sids, session_id());
?>
Because (even though your code says otherwise, and that the PHP documentation says otherwise), explode may not always return an array.
Another piece of information that may be useful is whether or not there was any error being reported, and, if so, what the error was.
Best of luck!
array_unshift()
accepts the array parameter by reference. This means it must actually be a variable, not an expression like array()
. It also means it will modify the variable you pass, not return a new array with the element added. Here's an example to illustrate this:
$array = array();
array_unshift($array, 42);
var_dump($array); // Array now has one element, 42
$sids = explode(",", $sid['sids']);
if (!is_array($sids)) {
$sids = array();
}
array_unshift($sids, session_id());
精彩评论