As part of a larger project, I'm receiving arrays in a form similar to this:
$out = array(
'2011' => ['Out', 'arrv'],
'2012' => ['Out'],
'2013' => ['Out'],
'2014' => ['Out'],
'2015' => ['Out'],
'2016' => ['some', 'none', 'test'],
'2017' => ['Out'],
'2018' => ['Out'],
'2019' => ['Out'],
'2020' => ['Out', 'did'],
'2021' => ['Out'],
'2022' => ['Out'],
'2023' => ['Out', 'did']
);
I need to remove the consecutive "Out" lines, but keep the first and the last. My failed attempt:
foreach ($out as $dtp=>$dto) {
if (count($dto) == 1) {
if (str_contains($dto[0], "Out")) {
$idx = array_search($dtp, array_keys($out));
echo "$dtp contains the string; index is $idx" . PHP_EOL;
var_dump($out[intval(array_keys($idx - 1))]);
if ((str_contains($out[$idx-1][0], "Out")) && (str_contains($out[$idx+1][0], "Out")) && count($out[$idx-1] == 1) && count($out[$idx+1] == 1)) {
array_splice($out, $idx, 1);
}
}
}
}
Counts are there since there may be multiple events per timestamp. Echo returns the correct index number, but var_dump always returns NULL.
Current debugging output:
2017 contains the string; index is 6
PHP Warning: array_keys() expects parameter 1 to be array, integer given in /home/redacted/pub/dbg2.php on line 28
PHP Notice: Undefined offset: 0 in /home/redacted/pub/dbg2.php on line 28
NULL
2018 contains the string; index is 7
PHP Warning: array_keys() expects parameter 1 to be array, integer given in /home/redacted/pub/dbg2.php on line 28
PHP Notice: Undefined offset: 0 in /home/redacted/pub/dbg2.php on line 28
NULL
2019 contains the string; index is 8
PHP Warning: array_keys() expects parameter 1 to be array, integer given in /home/redacted/pub/dbg2.php on line 28
PHP Notice: Undefined offset: 0 in /home/redacted/pub/dbg2.php on line 28
NULL
2021 contains the string; index is 10
PHP Warning: array_keys() expects parameter 1 to be array, integer given in /home/redacted/pub/dbg2.php on line 28
PHP Notice: Undefined offset: 0 in /home/redacted/pub/dbg2.php on line 28
NULL
2022 contains the string; index is 11
PHP Warning: array_keys() expects parameter 1 to be array, integer given in /home/redacted/pub/dbg2.php on line 28
PHP Notice: Undefined offset: 0 in /home/redacted/pub/dbg2.php on line 28
NULL
While I haven't shared the full source code, the output from the sample array would be this:
[
'2011' => ['Out', 'arrv'],
'2012' => ['Out'],
'2015' => ['Out'],
'2016' => ['some', 'none', 'test'],
'2017' => ['Out'],
'2019' => ['Out'],
'2020' => ['Out', 'did'],
'2021' => ['Out'],
'2022' => ['Out'],
'2023' => ['Out', 'did']
]
$outelements using$idx-- but$outhas no indexes, only year values as keys. Checking the previous, current, and next element values by$idxwill prove to be very difficult for you. Even worse, once you start successfully splicing out unwanted elements, you'll need to make sure that subsequent attempts to find previous and next elements are finding the correct element.