0

Working on a project where I need to loop through an array, find a specific value such as "Full Name:", for example, and echo that value, along with the next value in the array ( which is the name itself ). Then do the same for the next occurrence of "Full Name:", echo it and the next value, and so on.

I am still struggling to understand how "foreach" works, and not even sure that's what I'm supposed to use.

What I got so far:

<?php

$list = file_get_contents('list.txt');

$array = explode("\r\n", $list);

foreach ($array as $value) {

 not-sure-what-goes-here;

}

?>

Any help or pointers would be greatly appreciated.

Mirian
  • 9
  • 7

1 Answers1

0

It looks crazy but it does that you explain:

$array = [
    1 => 'asdfhjfg:',
    2 => 'name1',
    3 => 'Full name:',
    4 => 'name1',
    5 => 'sfdghgj',
    6 => 'dfhgj',
    7 => 'Full name:',
    8 => 'name2',
    9 => 'Full name:',
    10 => 'name3',
    11 => 'sdgfhjgh',
];
do {
    echo (current($array) === 'Full name:')?current($array) . ' ' . next($array) . '<br>':'';
} while (next($array));

Output:
Full name: name1
Full name: name2
Full name: name3

Yan Burtovoy
  • 198
  • 1
  • 2
  • 15
  • It works nicely, but I probably had to mention, that the array doesn't contain ONLY "Full name:" values. So basically, what I need the script to do, would be search for "Full name:" within the values, and do what you did. So it has to echo each occurrence of "Full name:", and the value immediately AFTER the "Full name:" value. Then jump to the next case, and so on. – Mirian Dec 13 '15 at 18:51
  • If extend input array with custom values this code still do what it does. – Yan Burtovoy Dec 13 '15 at 18:57
  • For some weird reason, when I try it with my list, it only finds the very FIRST "Full name:" value, echoes it out along with the name, and doesn't continue with the others after that. Triple checked it, everything is correct, the key/value pairs are identical like the first pair, that's echoed successfully, and it doesn't work. – Mirian Dec 13 '15 at 19:04
  • May be it's will be better if you provide example of input array? – Yan Burtovoy Dec 13 '15 at 19:05
  • I found the culprit - there were some blank lines in the text file that serves as an array, and, as a result, there were blank key values in the array. Once I removed those blank lines, the problem is gone - how do I prevent that from happening again ( remove all blank lines in the text file automatically )? – Mirian Dec 13 '15 at 19:14
  • for example like this: `file_put_contents('newFile.txt', implode('', file('list.txt', FILE_SKIP_EMPTY_LINES)));` – Yan Burtovoy Dec 13 '15 at 19:21
  • Thank you very much, already implemented a slightly different version, working like a charm now! – Mirian Dec 13 '15 at 19:28