PHP pass array without selected index - php

how to slice an array to pass it to a function. I cannot use unset because I need that array further. I know I can copy whole array to variable, however it's quite big and don't thing it's efficient. My code:
$list = array(0=>2123, 2=>1231, 7=>123123,...);
unset($list[0]); //I can't do this because I still need whole $list
$seats = $allocatingClass->allocateSeats($seatsNumber, $list); //here I need to slice $key from $list and pass $list without reiterating

If you need to keep index 0, store it, rather than storing the entire array elsewhere:
$tmp = $list[0];
Then splice the array:
$list = array_splice($list,1,count($list));
Then pass it to your function:
$seats = $allocatingClass->allocateSeats($seatsNumber, $list);
Then, when you need it, put back the value to the array:
$list[] = $tmp;
Edit: if you actually need to put it exactly at index 0, then you may want to unset the index 0 of the array instead of splicing it. If you can, however, push it at the end of the array just follow what is written above.
To clearify, if you need to LATER push back the element to index 0, do
unset($list[0]);
instead of the splice...
And to put back the element, do:
$list[0] = $tmp;

However you do it, a copy will be made when passing the array (unless you pass it by reference).
either use splice. or create a copy and shift one value.
after sending the copy variable, you can unset it so it wont keeptaking its space.
Edit :
The above solution is also viable. Though I suggest you use:
$tmp = array_shift($arr);
doStuf($arr);
array_unshift($arr, $tmp);

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.

Difference between array_push() and $array[] =

In the PHP manual, (array_push) says..
If you use array_push() to add one element to the array it's better to
use $array[] = because in that way there is no overhead of calling a
function.
For example :
$arr = array();
array_push($arr, "stackoverflow");
print_r($arr);
vs
$arr[] = "stackoverflow";
print_r($arr);
I don't understand why there is a big difference.
When you call a function in PHP (such as array_push()), there are overheads to the call, as PHP has to look up the function reference, find its position in memory and execute whatever code it defines.
Using $arr[] = 'some value'; does not require a function call, and implements the addition straight into the data structure. Thus, when adding a lot of data it is a lot quicker and resource-efficient to use $arr[].
You can add more than 1 element in one shot to array using array_push,
e.g. array_push($array_name, $element1, $element2,...)
Where $element1, $element2,... are elements to be added to array.
But if you want to add only one element at one time, then other method (i.e. using $array_name[]) should be preferred.
The difference is in the line below to "because in that way there is no overhead of calling a function."
array_push() will raise a warning if the first argument is not
an array. This differs from the $var[] behaviour where a new array is
created.
You should always use $array[] if possible because as the box states there is no overhead for the function call. Thus it is a bit faster than the function call.
array_push — Push one or more elements onto the end of array
Take note of the words "one or more elements onto the end"
to do that using $arr[] you would have to get the max size of the array
explain:
1.the first one declare the variable in array.
2.the second array_push method is used to push the string in the array variable.
3.finally it will print the result.
4.the second method is directly store the string in the array.
5.the data is printed in the array values in using print_r method.
this two are same
both are the same, but array_push makes a loop in it's parameter which is an array and perform $array[]=$element
Thought I'd add to the discussion since I believe there exists a crucial difference between the two when working with indexed arrays that people should be aware of.
Say you are dynamically creating a multi-dimensional associative array by looping through some data sets.
$foo = []
foreach ($fooData as $fooKey => $fooValue) {
foreach ($fooValue ?? [] as $barKey => $barValue) {
// Approach 1: results in Error 500
array_push($foo[$fooKey], $barKey); // Error 500: Argument #1 ($array) must be of type array
// NOTE: ($foo[$fooKey] ?? []) argument won't work since only variables can be passed by reference
// Approach 2: fix problem by instantiating array beforehand if it didn't exist
$foo[$fooKey] ??= [];
array_push($foo[$fooKey], $barKey);
// Approach 3: One liner approach
$foo[$fooKey][] = $barKey; // Instantiates array if it doesn't exist
}
}
Without having $foo[$fooKey] instantiated as an array beforehand, we won't be able to do array_push without getting the Error 500. The shorthand $foo[$fooKey][] does the heavy work for us, checking if the provided element is an array, and if it isn't, it creates it and pushes the item in for us.
I know this is an old answer but it might be helpful for others to know that another difference between the two is that if you have to add more than 2/3 values per loop to an array it's faster to use:
for($i = 0; $i < 10; $i++){
array_push($arr, $i, $i*2, $i*3, $i*4, ...)
}
instead of:
for($i = 0; $i < 10; $i++){
$arr[] = $i;
$arr[] = $i*2;
$arr[] = $i*3;
$arr[] = $i*4;
...
}
edit- Forgot to close the bracket for the for conditional
No one said, but array_push only pushes a element to the END OF THE ARRAY, where $array[index] can insert a value at any given index. Big difference.

How do I split a cookie using php

I have a cookie which I'm trying to split. The cookie is in this format:
key = val1,val2,val3 (where each value is separated by commas)
is there a way for me to split this in a loop so that I can directly access val3?
I've tried using the explode() function with no success.
for ($i = 0; $i < count($_COOKIE); $i++)
{
$ind = key($_COOKIE);
$data = $_COOKIE[$ind];
//I try and slit the cookie here
$cookie_temp = explode(",",$_COOKIE[$ind]);
//Here is where I wanted to display Val3 from the cookie
print $cookie_temp[2];
next($_COOKIE);
}
my code works fine but I then end up with all my Val3 in a large array. For example, my val3's are numbers and they get put in an array. Can I split this even further?
First of all, I'm hoping you know the name of the cookie you're trying to get the value of. Let's call it mycookie in the rest of my answer.
Second, just scrap the whole loop thing and just access $_COOKIE['mycookie'] directly.
Then, you can now call explode(",",$_COOKIE['mycookie']) to get the separate values.
Next, just get index 2 with [2] as you are in your current code.
As a shortcut, if the second one is the only one you need:
list(,,$val) = explode(",",$_COOKIE['mycookie']);
Assuming you are looping because you have multiple comma-separated cookie key/value groups, use a foreach() instead and with list() you can retrieve the third value with a direct assignment.
foreach ($_COOKIE as $key=>$value) {
list($v1, $v2, $v3) = explode("," $value);
echo $v3;
}
If you have only one cookie value to access, there is no need for the loop, and you can directly call explode(",", $_COOKIE['key'])
PHP 5.4 allows array dereferencing, whereby you can directly access the array element off of the explode() call, but this won't work in earlier PHP versions.
echo explode(",", $_COOKIE['key'])[2];

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;

php get 1st value of an array (associative or not)

This might sounds like a silly question. How do I get the 1st value of an array without knowing in advance if the array is associative or not?
In order to get the 1st element of an array I thought to do this:
function Get1stArrayValue($arr) { return current($arr); }
is it ok?
Could it create issues if array internal pointer was moved before function call?
Is there a better/smarter/fatser way to do it?
Thanks!
A better idea may be to use reset which "rewinds array's internal pointer to the first element and returns the value of the first array element"
Example:
function Get1stArrayValue($arr) { return reset($arr); }
As #therefromhere pointed out in the comment below, this solution is not ideal as it changes the state of the internal pointer. However, I don't think it is much of an issue as other functions such as array_pop also reset it.
The main concern that it couldn't be used when iterating over an array isn't an problem as foreach operates on a copy of the array. The PHP manual states:
Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself.
This can be shown using some simple test code:
$arr = array("a", "b", "c", "d");
foreach ( $arr as $val ){
echo reset($arr) . " - " . $val . "\n";
}
Result:
a - a
a - b
a - c
a - d
To get the first element for any array, you need to reset the pointer first.
http://ca3.php.net/reset
function Get1stArrayValue($arr) {
return reset($arr);
}
If you don't mind losing the first element from the array, you can also use
array_shift() - shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.
Or you could wrap the array into an ArrayIterator and use seek:
$array = array("foo" => "apple", "banana", "cherry", "damson", "elderberry");
$iterator = new ArrayIterator($array);
$iterator->seek(0);
echo $iterator->current(); // apple
If this is not an option either, use one of the other suggestions.

Categories