0

I'm not very experienced in using PHP, but I'm having a hard time thinking of a way to do this. I'm reading from a file and exploding on ":" as you can see here.

<?php
$datainfo = file('data.txt');
for($i = 0; $i < count($datainfo); $i++){
$expdata = explode(':', $datainfo[$i]);
}

?>

The issue is that I need to reference specific indexes of the resulted explosion like this.

<p> <?php echo $expdata[1] ?> </p>

I'm getting back an array of the last line inside the data.txt file. I know why It's happening, I just don't know how to get what I want here. (Sorry Very New). Data.txt contain the following.

name:Octopod Juice Stand
balance:20
price:0.5
customers:12
starting:2014-05-26
end: 2014-09-01
juice:15.25
fruit:10
5
  • Show the contents of data.txt Commented Feb 2, 2014 at 15:58
  • Do $expdata[] instead of $expdata. You are reassigning the variable with each loop thats why you get the last line only. Commented Feb 2, 2014 at 15:58
  • When I did that, it just echos out the word "Array" so I'm assuming it 's empty for some reason. Commented Feb 2, 2014 at 16:00
  • Do print_r($expdata) instead of echoing and see the array dump. Commented Feb 2, 2014 at 16:02
  • 1
    Because $expdata will be a two-dimensional array, so $expdata[1] will refer to array('balance', '20') Commented Feb 2, 2014 at 16:02

1 Answer 1

1

Change your code to

<?php
$datainfo = file('data.txt');
$expdata = array();

for($i = 0; $i < count($datainfo); $i++){
    $expdata[] = explode(':', $datainfo[$i]);
}

?>

And then to get the first label.

<p><?php echo $expdata[0][0]; ?></p>

Or the first value

<p><?php echo $expdata[0][1]; ?></p>
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, thank you for this, I noticed this reading one of the comments. I'm pretty tired and didn't even think about it being two dimensional.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.