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.
Related
This question has been asked a thousand times, but each question I find talks about associative arrays where one can delete (unset) an item by using they key as an identifier. But how do you do this if you have a simple array, and no key-value pairs?
Input code
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
foreach ($bananas as $banana) {
// do stuff
// remove current item
}
In Perl I would work with for and indices instead, but I am not sure that's the (safest?) way to go - even though from what I hear PHP is less strict in these things.
Note that after foreach has run, I expected var_dump($bananas) to return an empty array (or null, but preferably an empty array).
1st method (delete by value comparison):
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
foreach ($bananas as $key=>$banana) {
if($banana=='big_banana')
unset($bananas[$key]);
}
2nd method (delete by key):
$bananas = array('big_banana', 'small_banana', 'ripe_banana', 'yellow_banana', 'green_banana', 'brown_banana', 'peeled_banana');
unset($bananas[0]); //removes the first value
unset($bananas[count($bananas)-1]); //removes the last value
//unset($bananas[n-1]); removes the nth value
Finally if you want to reset the keys after deletion process:
$bananas = array_map('array_values', $bananas);
If you want to empty the array completely:
unset($bananas);
$bananas= array();
it still has the indexes
foreach ($bananas as $key => $banana) {
// do stuff
unset($bananas[$key]);
}
for($i=0; $i<count($bananas); $i++)
{
//doStuff
unset($bananas[$i]);
}
This will delete every element after its use so you will eventually end up with an empty array.
If for some reason you need to reindex after deleting you can use array_values
How about a while loop with array_shift?
while (($item = array_shift($bananas)) !== null)
{
//
}
Your Note: Note that after foreach has run, I expected var_dump($bananas) to return an empty array (or null, but preferably
an empty array).
Simply use unset.
foreach ($bananas as $banana) {
// do stuff
// remove current item
unset($bananas[$key]);
}
print_r($bananas);
Result
Array
(
)
This question is old but I will post my idea using array_slice for new visitors.
while(!empty($bananas)) {
// ... do something with $bananas[0] like
echo $bananas[0].'<br>';
$bananas = array_slice($bananas, 1);
}
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);
I'm trying to understand why, on my page with a query string,
the code:
echo "Item count = " . count($_GET);
echo "First item = " . $_GET[0];
Results in:
Item count = 3
First item =
Are PHP associative arrays distinct from numeric arrays, so that their items cannot be accessed by index? Thanks-
They can not. When you subscript a value by its key/index, it must match exactly.
If you really wanted to use numeric keys, you could use array_values() on $_GET, but you will lose all the information about the keys. You could also use array_keys() to get the keys with numerical indexes.
Alternatively, as Phil mentions, you can reset() the internal pointer to get the first. You can also get the last with end(). You can also pop or shift with array_pop() and array_shift(), both which will return the value once the array is modified.
Yes, the key of an array element is either an integer (must not be starting with 0) or an associative key, not both.
You can access the items either with a loop like this:
foreach ($_GET as $key => $value) {
}
Or get the values as an numerical array starting with key 0 with the array_values() function or get the first value with reset().
You can do it this way:
$keys = array_keys($_GET);
echo "First item = " . $_GET[$keys[0]];
Nope, it is not possible.
Try this:
file.php?foo=bar
file.php contents:
<?php
print_r($_GET);
?>
You get
Array
(
[foo] => bar
)
If you want to access the element at 0, try file.php?0=foobar.
You can also use a foreach or for loop and simply break after the first element (or whatever element you happen to want to reach):
foreach($_GET as $value){
echo($value);
break;
}
Nope -- they are mapped by key value pairs. You can iterate the they KV pair into an indexed array though:
foreach($_GET as $key => $value) {
$getArray[] = $value;
}
You can now access the values by index within $getArray.
As another weird workaround, you can access the very first element using:
print $_GET[key($_GET)];
This utilizes the internal array pointer, like reset/end/current(), could be useful in an each() loop.
I am trying to add a new key to an existing numerical indexed array using a foreach() loop.
I wrote this piece of code:
foreach($new['WidgetInstanceSetting'] as $row){
$row['random_key'] = $this->__str_rand(32, 'alphanum');
debug($row);
}
debug($new);
The first debug() works as I expected: the 'random_key' is created in the $new array.
Now, the problem is that the second debug() shows the $new array, but without the newly added key.
Why is this happening? How can I solve this problem?
$row ends up being a copy in the scope of the foreach block, so you really are modifying a copy of it and not what's in the original array at all.
Stick a & in your foreach to modify the $row array within your $new array by reference:
foreach($new['WidgetInstanceSetting'] as &$row){
And as user576875 says, delete the reference to $row in case you use that variable again to avoid unwanted behavior, because PHP leaves it around:
foreach($new['WidgetInstanceSetting'] as &$row){
$row['random_key'] = $this->__str_rand(32, 'alphanum');
debug($row);
}
unset($row);
debug($new);
Use the & to get a by reference value that you can change.
foreach($new['WidgetInstanceSetting'] as &$row){
$row['random_key'] = $this->__str_rand(32, 'alphanum');
debug($row);
}
debug($new);
You need to access the element by reference if you want to modify if within the array, as follows:
foreach($new['WidgetInstanceSetting'] as &$row) {
$row['random_key'] = $this->__str_rand(32, 'alphanum');
}
you are not creating random_key in $new array you are creating it in $row
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.