array_unshift() with empty array - php

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());

Related

How to fix json_decode out put

when in use json_decod with option "JSON_FORCE_OBJECT" its return out put index started with 0 and its true but i need to start the out put index with 1 so how i can fix my problem?
json_encode($request->get('poll_items'), JSON_FORCE_OBJECT)
The output result is and current BUT:
"{"0":"option1","1":"option2","2":"option3"}"
I need to return like this:
"{"1":"option1","2":"option2","3":"option3"}"
Thank you.
An easy solution would be to use array_unshift() and unset():
$array = $request->get('poll_items');
// Add an element to the beginning
array_shift($array, '');
// Unset the first element
unset($array[0]);
Now you're left with an associative array that starts with 1.
Here's a demo
My first question would be why do you need this to be 1 indexed instead of 0?
If this data is consumed outside of your control then you could map the data across to another array and encode that instead. For example:
$newArray = array();
foreach ($request->get('poll_items') as $index => $value) {
$newArray[++$index] = $value
}
$output = json_encode($newArray, JSON_FORCE_OBJECT);
NOTE: ++$index instead of $index++ as the latter will only alter the value after the line has computed.

Store Get-Values from form in Array PHP

I'm trying to store the users's input via the method get in an array to store it and further process it without overwriting the initial get-value. But I dont know how.. do I have to store them in a database to do that? Or can I just push every input into an array?
I believe the following should work for you... This will take all the $_GETs that you supply and put them in a new array so you can modify them without affecting the original $_GET array.
if(is_array($_GET)){
$newArr = $_GET; // modify $newArr['postFieldName'] instead of $_GET['postFieldName'] to preserve original $_GET but have new array.
}
That solution there will dupe the $_GET array. $_GET is just an internal PHP array of data, as is $_POST. You could also loop through the GETs if you do not need ALL of the GETs in your new array... You would do this by setting up an accepted array of GETs so you only pull the ones you need (this should be done anyways, as randomly accepting GETs from a form can lead to some trouble if you are also using the GETs for database/sql functions or anything permission based).
if(is_array($_GET) && count($_GET) > 0){
$array = array();
$theseOnly = array("postName", "postName2");
foreach($_GET as $key => $value){
if(!isset($array[$key]) && in_array($key, $theseOnly)){ // only add to new array if they are in our $theseOnly array.
$array[$key] = $value;
}
}
print_r($array);
} else {
echo "No $_GET found.";
}
I would just add to what #Nerdi.org said.
Specifically the second part, instead of looping through the array you can use either array_intersect_key or array_diff_key
$theseOnly = array("postName", "postName2");
$get = array_intersect_key( $_GET, array_flip($theseOnly);
//Or
$get = array_diff_key( $_GET, array_flip($theseOnly);
array_intersect_key
array_intersect_key() returns an array containing all the entries of array1 which have keys that are present in all the arguments.
So this one returns only elements you put in $theseOnly
array_diff_key
Compares the keys from array1 against the keys from array2 and returns the difference. This function is like array_diff() except the comparison is done on the keys instead of the values.
So this one returns the opposite or only elements you don't put in $theseOnly
And
array_flip
array_flip() returns an array in flip order, i.e. keys from array become values and values from array become keys.
This just takes the array of names with no keys (it has numeric keys by default), and swaps the key and the value, so
$theseOnly = array_flip(array("postName", "postName2"));
//becomes
$theseOnly = array("postName"=>0, "postName2"=>1);
We need the keys this way so they match what's in the $_GET array. We could always write the array that way, but if your lazy like me then you can just flip it.
session_start();
if(!isset($_SESSION['TestArray'])) $_SESSION['TestArray'] = array();
if(is_array($_GET)){
$_SESSION['TestArray'][] = $_GET;
}
print_r($_SESSION['TestArray']);
Thanks everybody for helping! This worked for me!

Best practice for clearing an array

I have an array that I would like to clear the values out of and I'm wondering what the best way to accomplish this is.
I tried setting it to nothing:
$array = array();
... later on
$array = "";
Afterwards I'll add new values to it later:
foreach($something as $thing):
$array[] = $thing['item'];
endforeach;
And it seems to have done what I needed it too. But after a quick search online I'm seeing a lot of recommendations to do the following instead:
unset($array);
$array = array();
Is there any difference between this action and the one I performed up top?
Setting $array to "" sets your variable to a string value, and unset removes the variable. Since you are just trying to clear the array, then $array = array() should be good enough.
I believe that array() explicitly defines it as an array. Your first statement $array = "" sets it to an empty string. Using unset will "reset" the variable, so it's neither a string or array until you assign a value to it, and $array = array() simply defines it as a new blank array.

change last key name from array in php

i want to be able to change the last key from array
i try with this function i made:
function getlastimage($newkey){
$arr = $_SESSION['files'];
$oldkey = array_pop(array_keys($arr));
$arr[$newkey] = $arr[$oldkey];
unset($arr[$oldkey]);
$_SESSION['files'] = $arr;
$results = end($arr);
print_r($arr);
}
if i call the function getlastimage('newkey') it change the key!but after if i print the $_SESSION the key is not changed? why this?
When you set $arr = $_SESSION['files'], you are actually making a copy of $_SESSION['files']. Everything you do to $arr is not done to the original.
Try this:
$arr =& $_SESSION['files'];
Note the ampersand after the equals sign. That will make $arr a reference to $_SESSION['files'], and your updates to $arr will affect $_SESSION['files'] as well, since they both reference the same content.
The other solution is of course to just copy the array back by putting $_SESSION['files'] = $arr; at the end of your function.
Wow, your code is a mess!
1) You're setting $_SESSION in a new array. In order for your changes to take affect, you'll need to set back to your original $_SESSION array, otherwise your new array will just be forgotten.
2) It would be easier to simply array_pop() to get the last element and set it to the new key, rather than wasting the time to fetch all the keys and pop the last key off, then fetch the value from the array again. The old key value is worthless.
try update the session
$_SESSION['files'] = $arr;

Make 1d Array from 1st member of each value in 2d Array | PHP

How can you do this? My code seen here doesn't work
for($i=0;i<count($cond);$i++){
$cond[$i] = $cond[$i][0];
}
It can be as simple as this:
$array = array_map('reset', $array);
There could be problems if the source array isn't numerically index. Try this instead:
$destinationArray = array();
for ($sourceArray as $key=>$value) {
$destinationArray[] = $value[0]; //you may want to use a different index than '0'
}
// Make sure you have your first array initialised here!
$array2 = array();
foreach ($array AS $item)
{
$array2[] = $item[0];
}
Assuming you want to have the same variable name afterwards, you can re-assign the new array back to the old one.
$array = $array2;
unset($array2); // Not needed, but helps with keeping memory down
Also, you might be able to, dependant on what is in the array, do something like.
$array = array_merge(array_values($array));
As previously stated, your code will not work properly in various situation.
Try to initialize your array with this values:
$cond = array(5=>array('4','3'),9=>array('3','4'));
A solution, to me better readable also is the following code:
//explain what to do to every single line of the 2d array
function reduceRowToFirstItem($x) { return $x[0]; }
// apply the trasnformation to the array
$a=array_map('reduceRowTofirstItem',$cond);
You can read the reference for array map for a thorough explanation.
You can opt also for a slight variation using array_walk (it operate on the array "in place"). Note that the function doesn't return a value and that his parameter is passed by reference.
function reduceToFirstItem(&$x) { $x=$x[0]; }
array_walk($cond, 'reduceToFirstItem');
That should work. Why does it not work? what error message do you get?
This is the code I would use:
$inArr;//This is the 2D array
$outArr = array();
for($i=0;$i<count($inArr);$i++){
$outArr[$i] = $inArr[$i][0];
}

Categories