PHP $var += array('x','y') - php

Sorry to ask, it's only for my understanding !
I just start learning php.
I added some values from different method to an array and it come to a strange problem that i can't find an answer on the web.
(sorry if it's stupid, i just want to know why it do that.)
My PHP/HTML code:
<?php
$test[] = 1;
$test += array('2','3','4');
$test += array('4in4',5 => '5');
$test[] = 6;
$test[] += 7;
?>
<!doctype html>
<html lang="fr-CA" >
<head>
<meta charset="UTF-8">
<body>
<?php echo '<h1>Test de Tableau</h1>','<br>',
'$test[0] = ',$test[0],'<br>',
'$test[1] = ',$test[1],'<br>',
'$test[2] = ',$test[2],'<br>',
'$test[3] = ',$test[3],'<br>',
'$test[4] = ',$test[4],'<br>',
'$test[5] = ',$test[5],'<br>',
'$test[6] = ',$test[6],'<br>',
'$test[7] = ',$test[7],'<br>',
'<h4>count = ',count($test),'/8</h4>'; ?>
</body>
And here is the result :
Test de Tableau
$test[0] = 1
$test[1] = 3
$test[2] = 4
$test[3] =
Notice: Undefined offset: 3 in /opt/lampp/htdocs/mhx/test/index.php on line 26
$test[4] =
Notice: Undefined offset: 4 in /opt/lampp/htdocs/mhx/test/index.php on line 27
$test[5] = 5
$test[6] = 6
$test[7] = 7
count = 6/8
Thanks to answer !
MHX

This may have already been answered by this post: + operator for array in PHP?
Essentially, here's what's happening. You initialized your array:
$test = [0 => 1];
Next, you're adding a new array to it:
[0 => '2', 1 => '3', 2 => '4'];
The first index already exists, so it's skipped giving us:
$test = [0 => 1, 1 => '3', 2 => '4'];
Now, you're adding another array:
[0 => '4in4', 5 => '5'];
Again, the first index exists, so we get:
$test = [0 => 1, 1 => '3', 2 => '4', 5 => '5'];
By now, you can see that offsets 3 and 4 are missing, hence your notices above. Also, the internal pointer is now at 6 since the last element added was at 5.
You then add 6, followed by 7, giving us the final array:
$test = [0 => 1, 1 => '3', 2 => '4', 5 => '5', 6 => 6, 7 => 7];
I hope this helps.
EDIT: When adding another element to an array, you can just write it like this:
$test[] = 1;
If you need to merge two arrays, look at array_merge():
$test = array_merge($test, [1, 2, 3]);
Cheers!

Related

Create dynamic sub array from a big one [duplicate]

This question already has answers here:
PHP: How to split array into 2 parts?
(6 answers)
Closed 10 months ago.
I have an array, made by using explode and the delimiter #. I'm trying without success to create from this big array in PHP subarrays (the number of subarrays is not fixed and could vary). The goal is to make every 10 # a new sub array and store in all the values between 0 - 9, 10 - 19, etc...
Here my big array where the PHP has to work on : the ( ) are just comment to be more clear, in the code there is only #
#ACT/A (line 1)
#XXX (2)
#2 (3)
#51,6844 (4)
#50,7000 (5)
#101,40 (6)
#-1,97 (7)
#-1,91 (8)
#-0,61 (9)
#3,34 (10)
#ACT/B (11
#X
#4
#68,86750
#63,2700
#253,08
#-22,39
#-8,13
#-0,41
#8,27 (line 20)
#ACT/C
#X
#15
#10,33132
#4,18
#62,70
#-92,27
#-59,54
#0,00
#2,03
My PHP code (which is not working) :
$start = 1;
$equities = explode("#", $allEquities); // split the big array here
//$howManyEquities is a number between 1 and X, only int, not float)
while($start <= $howManyEquities) // doing the loop for each equities counted (could vary from 1 to x)
{
$array[$howManyEquities] = $equities[0]; // trying to store in a array the result (line 1 from the example above, and then line 11, etc...)
$equities = $equities[$start * 10]; // trying to prepare next loop, start (1) * 10 = 11 to catch next time result from line 11
$start++;
}
To sum up, I'm probably very not clear and I apologize. Here an example of the dynamic array I want from the code (I tried foreach loop but didn't seem to work) :
BigArray (the number of key inside vary according to the number of equity) = (
subArray1 = (ACT/A, XXX, 2, 51,6844, etc from line 1 to 10)
subArray2 = (ACT/B, X, 68,86750, etc from line 11 to 20)
subArray3 = (ACT/C, etc)
subArrayX = (ACT/X, etc)
It could be resumed by every ten first values inside a first array, the next ten in another array, and so on until we cover all the big array (that's why I tried $start * 10 in my code). I have to precise that if $howManyEquities = 7 by example, there will be 70 #, if = 5 there will be 50 # and so on.
EDIT : Solution thanks to #user3783243
while($start <= $howManyEquities)
{
$newArray = array_chunk($equities, 10);
$start++;
}
Don't hesitate if you need more information, thanks for reading and enjoy week-end !
Respectfully
As #user3783243 said, array_chunk does the job.
Source string:
$string = '#ACT/A (line 1)
#XXX (2)
#2 (3)
#51,6844 (4)
#50,7000 (5)
#101,40 (6)
#-1,97 (7)
#-1,91 (8)
#-0,61 (9)
#3,34 (10)
#ACT/B (11
#X
#4
#68,86750
#63,2700
#253,08
#-22,39
#-8,13
#-0,41
#8,27 (line 20)
#ACT/C
#X
#15
#10,33132
#4,18
#62,70
#-92,27
#-59,54
#0,00
#2,03';
The code:
// Explode.
$array = explode('#', $string);
// Should trim all values to f.e. remove new lines.
$array = array_map('trim', $array);
// Should filter empty values (due to empty lines in string).
$array = array_filter($array, 'strlen');
// Split into chunks.
$array = array_chunk($array, 10, true);
Output:
echo var_export($array, true) . PHP_EOL;
// [
// 0 => [
// 1 => 'ACT/A (line 1)',
// 2 => 'XXX (2)',
// 3 => '2 (3)',
// 4 => '51,6844 (4)',
// 5 => '50,7000 (5)',
// 6 => '101,40 (6)',
// 7 => '-1,97 (7)',
// 8 => '-1,91 (8)',
// 9 => '-0,61 (9)',
// 10 => '3,34 (10)',
// ],
// 1 => [
// 11 => 'ACT/B (11',
// 12 => 'X',
// 13 => '4',
// 14 => '68,86750',
// 15 => '63,2700',
// 16 => '253,08',
// 17 => '-22,39',
// 18 => '-8,13',
// 19 => '-0,41',
// 20 => '8,27 (line 20)',
// ],
// 2 => [
// 21 => 'ACT/C',
// 22 => 'X',
// 23 => '15',
// 24 => '10,33132',
// 25 => '4,18',
// 26 => '62,70',
// 27 => '-92,27',
// 28 => '-59,54',
// 29 => '0,00',
// 30 => '2,03',
// ],
// ]

Undefined offset:1

$aa = Input::get('AccountOpeningDate' . $i);
$dateinfo = explode("-", $aa);
$testDay = Carbon::createFromDate($dateinfo[0], $dateinfo[1],
$dateinfo[2], 'UTC');
$actualDate = $testDay->setTimezone('+6:00');
when I run this code then I get an output.But it cause an error that like the image below.
ErrorException in MemberController.php line 532:
Undefined offset: 1
in MemberController.php line 532
at HandleExceptions->handleError('8', 'Undefined offset: 1', 'C:\xampp\htdocs\timf\app\Http\Controllers\MemberController.php', '532', array('id' => '4001-5088-0565', 'memberdata' => object(Member), 'somityDay' => object(Zone1), 'i' => '2', 'aa' => '', 'dateinfo' => array(''), 'testDay' => object(Carbon), 'actualDate' => object(Carbon), 'producttype' => '2', 'memberaccount' => object(Accountstable), 'valsa' => object(Product), 'AccNameSub' => 'MSSM', 'accnumber' => 'MSSM.4001-5088-0565', 'k' => '13', 'SavingSetup' =>
This code is written in laravel 5.1.
$aa = Input::get('AccountOpeningDate' . $i);
Here $aa has no data in case of any conditions. So the array $dateinfo remaining empty. I have fixed the problem by ensuring $aa data not empty.
now the code is running well.
There may be a comma missing in your first line of code.

Adding an array of values to an existing array

I've got a foreach where I create an array out of id's, based on the submitted selected checkboxes from my form (which are `checkbox[$id]. So I end up with:
Where 1, 2 and 3 are the submitted id's from the form. So far so good.
Now I also have an input field amount[$id]in my form. When selecting a checkbox, I can enter an amount for that row and submit the results. I need to add the values of amount to my array if id's. My end result should look like this:
[1 => ['amount' => '10'], 2 => ['amount' => '12'], 3 => ['amount' => '5'] // And so on
I tried merging, and array_push, but I seem to be doing it wrong, since I cannot figure it out. Any pointers?
Something like this should work:
$result = [];
$ids = [1,2,3]; // I suppose it is `$_POST['ids']`
$amounts = [1 => 10, 2 => 11, 3 => 22]; // I suppose it is `$_POST['amount']`
foreach ($ids as $id) {
if (!empty($amounts[$id])) {
$result[$id] = ['amount' => $amounts[$id]];
}
}
Using array_combine as advised in comments can be used only if sizes of arrays are equal. So if you have something like:
$ids = [1,2,4];
$amounts = [1 => 10, 2 => 11, 3 => 0, 4 => 22];
print_r(array_combine($ids, $amounts)); // PHP Warning
And second fact - array_combine won't create values as arrays. So
$ids = [1,2,3];
$amounts = [1 => 10, 2 => 11, 3 => 10];
print_r(array_combine($ids, $amounts)); // no subarrays here

PHP array - `array_splice` issue

I am working with PHP array to store the comma separated values of product Ids and then in turn use them to show as recent seen products.
Implementation is as below:
$product_data = array();
$array_ids_a_display = array();
$check_status = array();
$array_check= array();
$_COOKIE['Pr'] = [1,2,3,4,5,6,7,8]
Then i am Taking the last point of the stored string
$array_check = explode(',',substr($_COOKIE['IdProduto'],0,-1));
Now, i check of products are enabled then store them into one other array
foreach($array_check as $id_a_checar){
$check_status = $this->model->getProduct($id_a_checar);
if($check_status['status']){ // If status is 1
$array_ids_a_display[$contprods++] = $id_a_checar;
}
}
if($s['limit']>count($array_ids_a_display)){
//If the number of valid products < number of products of module
$s['limit'] = count($array_ids_a_display);
//will show,then reconfigures the number of products that will show
}
}
where $s['limit'] comes from backend , let us say 6 to limit the number of products.
Now, i will reverse the array to get latest visited product at first place like as
$last_ended = array_reverse($array_ids_a_display);
array_splice($last_ended,0,(int)$s['limit']);
foreach ($last_ended as $result) {
$product_data[$result] = $this->product->getProduct($result);
}
Now here comes the problem, as i am only getting 3 products in $product_data array but is shall get 6 products.
I hope that there is issue with array_splice because if i will comment array_splice then i am getting all stores products in cookies as result.
Mysql query is working very fine.
Please advice how to get latest 6 values from array
Here you are:
$last_ended = array(1, 2, 3, 4, 5, 6, 7, 8);
$last_ended = array_reverse($last_ended);
//here is what you missed:
$last_ended = array_splice($last_ended, 0, 6);
print_r($last_ended);
//returns Array ( [0] => 8 [1] => 7 [2] => 6 [3] => 5 [4] => 4 [5] => 3 )
You need to assign your $last_ended var into array_splice result.
<?php
// Get the last 6 entries of an array...
$arr = array(
1,
2,
3,
4,
5,
6,
7,
8
);
$entries = array_splice($arr, -6);
// returns [3, 4, 5, 6, 7, 8]
}
$maxResultLength = 6;
$someArray = [1,2,3,4,5,6,7,8,9,10,'a','b','c','d','e','f','g','h'];
$startIndex = (count($someArray) >= $maxResultLength) ? count($someArray) - $maxResultLength : 0;
$lastSixElements = array_slice($someArray, $startIndex, $maxResultLength);
or
$maxResultLength = 6;
$someArray = [1,2,3,4,5,6,7,8,9,10,'a','b','c','d','e','f','g','h'];
$lastSixElements = array_splice($someArray, -6);

PHP multidimensional array counter

Im trying to make a multidimensional array with two columns. Name and Counter. I can do a single array with all the names. But I dont know how to make it multidimensional and be able to still update the counters. Code i got so far is
if (!in_array($prodname, $da)){
array_push($da, $prodname);
}
and then I can dump it back out with a foreach. How do I make it two dimensional? How can I say alright this exists update the old value? etc.
If you only need name and counter then you should just be able to use a normal array:
$nameCountArray = array();
foreach($names as $name){
if(!array_key_exists($name,$nameCountArray)){
$nameCountArray[$name] = 1;
}else{
$nameCountArray[$name] = $nameCountArray[$name] + 1;
}
}
If you do need multidimensional arrays these are just arrays of arrays and can be accessed as such. A good example of this is using a 2d array to store locations (say on a 3 by 3 grid):
$twoDArray = array(
0 => array(0 => 1,
1 => 4,
2 => 7),
1 => array(0 => 2,
1 => 5,
2 => 8),
2 => array(0 => 3,
1 => 6,
2 => 9)
);
//Grab the item at 1,2
$item = $twoDArray[1][2];//Will give '8'
Supposing you want $da to look like this:
Array(
"name1" => array("score1" => 80, "score2" => 100),
"name2" => array("score1" => 50, "score2" => 60),
"name3" => array("score1" => 90, "score2" => 80),
...
)
Then all you need to do is something like:
function setScore($prodName, $scoreName, $score)
{
global $da;
if (!array_key_exists($prodName, $da)) {
$da[$prodName] = array();
}
$da[$prodName][$scoreName] = $score;
}
setScore("name1", "score1", 80);
setScore("name1", "score2", 100);
setScore("name2", "score1", 50);
...
Unless I'm misunderstanding your question, which is very possible.

Categories