I’ve got something I think it is a 3 dimensional array:
$var = '1,Tony,186|2,Andrea,163|3,Peter,178|4,Sally,172';
So there are 2 arrays packed inside the variable. First is separated by | the second one by ,
What I need to do is: separate them and then check for an ID located before the name and give me single variables of the rest. I tried it like this:
<?php $personid = 3; $var = '1,Tony,186|2,Andrea,163|3,Peter,178|4,Sally,172'; $array = explode('|',$var); foreach($array as $values) { $arr = explode(",",$values); foreach($arr as $value) { if($value[0] == $personid) { $id = $value[0]; $name = $value[1]; $height = $value[2]; $killloop = 1; } } if($killloop == 1) { break; } } echo 'ID: '.$id.'<br> Name: '.$name.'<br> Height: '.$height; ?>
But all i get then is:
ID: 3 Name: Height:
Can anyone help out?
Advertisement
Answer
There is no need loop Into Second Array, You already have defined positions. Always Use break statement to end a Loop immediately, Its a good practice
<?php $personid = 3; $var = '1,Tony,186|2,Andrea,163|3,Peter,178|4,Sally,172'; $array = explode('|',$var); foreach($array as $values) { $arr = explode(",",$values); if(!empty($arr) && $arr[0] == $personid){ $id = $arr[0]; $name = $arr[1]; $height = $arr[2]; break; } } echo 'ID: '.$id.'<br> Name: '.$name.'<br> Height: '.$height; ?>