How to push into an array and not reset index PHP - php

I have and array and i need to push a value into the first index(0).
array:3 [▼
4 => "test1"
5 => "test2"
6 => "test3"
]
I need the indexes to stay like this, so the array will become like below. Since the indexes are the IDS of the values.
array:3 [▼
0 => "None selected"
4 => "test1"
5 => "test2"
6 => "test3"
]
To populate array:
$accuGroups = UpselGroup::where('accu_group','1')->with('UpselProducts.products')->pluck('naam','id')->toArray();
What i tried:
$accuGroups = array_merge([0 => 'None selected'], $accuGroups);
outcome (not what i want):
array:4 [▼
0 => "None selected"
1 => "test1"
2 => "test2"
3 => "test3"
]
Any help is appreciated
thanks

array_merge() function, and the keys are integers, the function returns a new array with integer keys starting at 0 and increases by 1 for each value
so use like this :
$accuGroups[0]="None selected";

Try this
$none_selected = array(
0 => 'None selected');
$accuGroups = $none_selected + $accuGroups;

you can try this
<?php
$queue = array("test1", "test2","test3", "test4");
array_unshift($queue, "None selected");
echo "<pre>";
print_r($queue);
?>

$accuGroups[0]="Not Selected.";
$accuGroups[6]="Not Selected.";
The array will reset its index value with given Value;

Keep another value which you have to merge as array and add it to first array and you will get result.
$a=['4' => "test1", '5' => "test2",'6' => "test3"];
$b=['0'=>'Not Selected'];
$c=$b+$a;
in $c you will get result as per your requirement.

You can try this
<?php
$array = array('4' => 'test1','5' => 'test2', '6' => 'test3');
$add = array('0'=>'None selected');
$final = $add + $array;
echo "<pre>";print_r($final);die;
?>

Related

convert array of arrays into comma separated list with unique values - PHP

I have an array that looks like below:
$var[] = ^ array:4 [▼
0 => array:1 [▼
0 => "apple"
]
1 => array:1 [▼
0 => "apple"
1 => "grape"
]
2 => array:1 [▼
0 => "orange"
]
3 => array:1 [▼
0 => "banana"
]
]
Is there a way to convert this array into comma separated list with unique values as below?
$var = "apple,grape,orange,banana"
I tried implode(', ',$var) but it's not working as expected. Any help pls?
Update: My sub-array may have more than 1 element. It's dynamic.
This produces the results given the expected input. Basically array_column get's the first item from each item of the array (0 based). Then array_unique on that will simply get the values without duplicates.
$arr = [
['apple'],
['apple'],
['banana'],
['pie'],
];
print_r(array_unique(array_column($arr, 0)));
EDIT: since there might be more than one item in the inner arrays, there's no shame in doing a non one-liner solution:
$result = [];
foreach ($arr as $row) {
foreach ($row as $item) {
if (array_search($item, $result) === false) {
$result[] = $item;
}
}
}
print_r($result);
There's also a one-liner solution:
$result= array_unique(call_user_func_array('array_merge', $arr));
cf. https://stackoverflow.com/a/14972714/13720553

Searching string nested array - PHP

I have a question regarding nested array
dd($this->forest);
it give me this:
array:2 [▼
0 => array:3 [▼
"id" => 12
"location" => 'east'
"type" => 'reservation'
]
1 => array:3 [▼
"id" => 13
"location" => 'west'
"type" => 'rainforest'
]
2 => array:3 [▼
"id" => 14
"location" => 'north'
"type" => 'rainforest'
]
]
so I want to search 'swamp' and 'mangrove' like "type" => 'swamp' or "type" => 'mangrove' but these type is not in the array of $this->forest. So, I have used in_array to sort it out.
$this->typeOfForest = '';
foreach($this->forest as $item){
if(!in_array('swamp', $item)){
$this->typeOfForest = 'swamp_not_found';
break;
}
elseif(!in_array('mangrove', $item)){
$this->typeOfForest = 'mangrove_not_found';
break;
}
}
dd($this->typeOfForest);
but when I dd($this->typeOfForest);
it will not set as $this->typeOfForest = 'swamp_not_found'; instead $this->typeOfForest = 'mangrove_not_found';
Also, when I insert new data 'swamp' into array $this->forest; and run again in_array function it will give me $this->typeOfForest = 'swamp_not_found'; instead of $this->typeOfForest = 'mangrove_not_found';
Thank you!
As said in the comments, the in_array function does not work with a multidimensional array. You need to use the array_column function to get all the types and then just do a lookup.
$this->typeOfForest = null;
$types = array_column($this->forest,'type');
if(in_array('swamp', $types)){
$typeOfForest = 'swamp found';
}elseif(in_array('mangrove', $types)){
$typeOfForest = 'mangrove found';
}
var_dump($this->typeOfForest);
You are using in_array function, it just searches for a given value in every index of the array, But as you have a 2D array, So in_array cant find any index with value JUST 'swamp', so your first IF condition becomes TRUE.
You can do like this:
$this->typeOfForest = '';
foreach($this->forest as $item){
if ($item['type'] == 'swamp'){
$typeOfForest='swamp found';
break;
}
elseif($item['type'] == 'mangrove'){
$typeOfForest='mangrove found';
break;
}
}
var_dump($this->typeOfForest);

Undefined index error while key exists in array

I'm pulling my hair on a proble which seems very simple, but I can't find a solution.
I have a simple $row array here :
array:2 [▼
"reference" => "ABCDEF"
"quantity" => "10"
]
I'm trying to parse it and retrieve quantities per reference using :
$line = [
'ref' => strtoupper($row["reference"]),
'quantity' => $row["quantity"]
];
I'm looping through array of lines using this code:
foreach ($rows as $row) {
$line = [
'ref' => strtoupper($row['reference']),
'quantity' => $row['quantity']
];
}
As a test, my main array $rows has 2 lines :
^ array:3 [▼
0 => array:2 [▼
0 => "ABCDEF"
1 => "10"
]
1 => array:2 [▼
0 => "WXCVBN"
1 => "3"
]
2 => array:1 [▼
0 => null
]
]
However, I'm getting the following error :
Undefined index: reference
Strangely enough, if I comment out the
'ref' => strtoupper($row["reference"]),
line, I can get the "quantity" value with no issue...
I know the key is in there, since the debug of the $row object gives the above result.
It must be dead simple... but I can't find the solution...
If anyone could please help ?
So apparently the $row variable a row from a bigger array that is used in a foreach loop.
This might be the solution to your problem.
$array = [
[ "reference" => "ABC", "quantity" => "10"],
[ "reference" => "ABC", "quantity" => "10"],
[ "reference" => "ABC", "quantity" => "10"],
];
$line[] = '';
foreach($array as $row)
{
$line['ref'] = $row['reference'];
$line['quantity'] = $row['quantity'];
}
In this example $array is your bigger array, i use it to test the example.
After that i create a empty array $line to append the "new" data.
Could you try this?
Edit:
After taking a look at your loop and the array i noticed that your array doesnt have a reference key. Can you try strtoupper(row[0])?
Viewing your code seems that you convert $row array to $line without rewrite key in new array.
your code
foreach ($rows as $row) {
$line = [
'ref' => strtoupper($row['reference']),
'quantity' => $row['quantity']
];
}
With your rewrite you can access $line data by index, not by key
array:3 [▼
0 => array:2 [▼
0 => "ABCDEF"
1 => "10"
]
...
]
My solution
If you want to access your $line data by key, you need to rewrite your loop as:
foreach($rows as $rowData) {
foreach($rowData as $rowKey => $rowValue) {
$data = [
'ref' => $rowKey => strtoupper$($rowValue),
'quantity' => $row['quantity']
];
}
$line[] = $data;
}

Unable to add 2 associative arrays

I am trying to add 2 associative arrays, but the new array only comes with an index for the second array.
This is what I am doing
$array = ['name' => 'address', 'value' => 'us'];
$arr = ['name' => 'joe', 'value' => 'doe'];
$arr[] = $array;
This is the result
array:3 [▼
"name" => "joe"
"value" => "doe"
0 => array:2 [▶]
]
I am expecting something like this
array:2 [▼
0 => array:2 [▶]
1 => array:2 [▶]
]
As you can see, there is no index for the first array, thus making the count 3 instead of 2. Please how do I fix this?
Just create another array and add the 2 arrays to it:
$newAr = [];
$newAr[] = $array;
$newAr[] = $arr;
var_dump($newAr);

Misunderstanding of array_values

I've a problem to unerstand correctly array_values, when I do:
$array[] = 'data1'; // I want [0 => 'data1']
unset($array[0]); // I want []
$array = array_values($array); // I want [] but keys resetted
$array[] = 'data2'; // I want [0 => 'data2']
$array[] = 'data3'; // I want [0 => 'data2', 1 => 'data3']
dump($array);
I've the result:
array:2 [▼
1 => "data2"
2 => "data3"
]
But I'll want:
array:2 [▼
0 => "data2"
1 => "data3"
]
Maybe someone can explain it to me ? Because I'm a little lost :-/
For exemple, if I've an array with 10 values in, remove the 3rd value, and do an array_values on, it works well.
But if I remove the last value from an array, then when I do a array_value, the next value I add, always have id 1 and not 0.
This behaviour has been already reported as a bug: https://bugs.php.net/bug.php?id=75433 and (apparently as the result of this post) also: https://bugs.php.net/bug.php?id=75653

Categories