Breaking a file with explode - php

Today I figured out how to explode a file into fragments. I got it done with the following piece of code.
<?php
$file = file('url here');
foreach ($file as $files)
{
list($example) = explode(',', $file);
}
?>
But when I echo the $example out, I am just getting a text saying "Array" as the output. The text file which I inputted looks like the following
1,2,3,4,5
I expect the output to be like the following
1
2
3
4
5
So is it possible. If yes please help me out

That is because $example is an array. That is why "Array" is returned. Print it like this instead:
foreach($example as $item) echo $item,"\n";

Use <br> after each item for HTML or PHP_EOL for text files
foreach ($example as $item)
{
echo "$item<br>".PHP_EOL;
}

$example will be an array, so you need to use print_r() or specify a index to echo:
echo $example[1];
Ideally, to print all the elements, you could simply do another loop:
foreach($example as $element){echo $element."<br>";}

I think you have got two issues here, and you should solve one after the other. This is one I could spot:
Instead of:
list($example) = explode(',', $file);
Try with:
$example = explode(',', $file);
Also take care, that if you have multiple lines, you'll overwrite $example, so you might want to output it inside the foreach loop already.

Related

How to put an Array Value to echo individually

I want to echo the array on a different location but I cannot make it to work.
i can echo the array if I do these
foreach($domain as $value) {
echo $value;
}
bot cannot echo it individually
foreach($domain as $value) {
$domainame[] = $value;
}
echo '<p> your first domain' .$domainname[0];
echo '<p> your last domain' .$domainname[5];
There are many ways to do this:
var_export($array);
var_dump($array);
print_r($array);
For each of the above it's useful to first ( when outputting to html )
echo "<pre>";
A pre tag to preserve the white space. Each one of these have some uniqueness to them. While I cant cover them all.
var_export - outputs valid PHP comparable text, so you can paste an array right into your code after outputting it with this. It has a second argument $string = var_export($array,true) that will return it as a string
var_dump - tells you the type of variable, such as int, array etc..
print_r - is more "human" readable.
If you want to get really wild you can use, array_map instead of a loop:
array_map(function($item){
echo $item;
}, $array);
At first one would think you could simply do
array_map('echo', $array);
But, alas echo is not a real function, it's a language construct, so you have to wrap it in a closure. Compare this to var_dump
array_map('var_dump', $array )
Works just fine.
And last but not least you could always do
echo json_encode($array);
But that probably won't be to readable.
I am sure there are some I am forgetting.
UPDATE
I thought you just wanted to generally output it. Anyway, you can use array_map
array_map(function($item){
echo "<p> your first domain{$domainame[0]}</p>"; //dont forget the typo
}, $array);
I think #Alive to Die, got it with the typo. But, if you output it using any of the above you would see it was empty.
One thing I should mention, as you should have gotten a warning for this, when developing you should have error reporting turned on ether globally in the php.ini or at least in the file your working on
<?php
error_reporting(-1); //error level E_ALL
ini_set('display_errors', 1); //output errors
you can simply write:
echo '<p> your first domain' .$domain[0];
echo '<p> your last domain' .$domain[5];
no point of looping at all!
you have to do like this
$i = 0;
foreach($domain as $value){
$domainame[$i] = $value;
$i++;
}
and now you can do this
echo '<p> your first domain' .$domainname[0];

Displaying data from a CSV file with multi-dimensional PHP array

I'm trying to pull data from a CSV file that contains vehicle make, model, mileage etc...
Using this example from php -
<?php
$csv = array_map('str_getcsv', file('csv/csvin.csv'));
array_walk($csv, function(&$a) use ($csv) {
$a = array_combine($csv[0], $a);
});
array_shift($csv);
foreach($csv as $car){
foreach($car as $key=>$value){
echo "<div id='car'>".$key.":".$value."</div></br>";
}
}
?>
This is the array I get -
BodyStyle:"Station Wagon"
"DaysInStock":"27"
"Make":"Toyota"
"Model":"Prius v"
"MSRP":"0"
"SellingPrice":"26995"
"StockNumber":"387515"
"Trim":"Three"
"VIN":"JTDZN3EU9E3306528"
"Year" :"2014"
Now when I attempt to manipulate it or pull any individual values I simply cannot. How would I go about displaying this information with HTML tags for each value?
I have tried this:
print_r ($csv[0]['Make'];
echo $csv[0]['Make'];
Just to try and display a value but still nothing. I noticed for some reason the "BodyStyle" doesn't contain quotes like the rest so something definitely seems fishy.
From here how would I strip the quotes and break out each value?
This is the error being thrown -
Invalid argument supplied for foreach() in
Thanks in advance!
foreach($csv as $car){
echo "<tr><td>Make:</td><td>".$car['Make']."</td></tr>";
}
alternatively:
foreach($csv as $car){
foreach($car as $key=>$value){
echo "<tr><td>".$key."</td><td>".$value."</td></tr>";
}
}
alternatively:
echo $csv[0]['Make'];
Try this one :
print_r ($csv[0]['Make']);
Basically the $csv variable is an array, to get its values you have to use the loop function, something like :
foreach ($csv as $data) {
foreach ($data as $index => $value) {
if ($index == "make") {
echo $value;
}
}
}
If you notice it a bit, the outer array is called indexed array (array with indexes) and to traverse the values use foreach ($csv as $data), while the inner array is called associative array (this array does not use number as index, but a name), and to traverse it use foreach ($data as $index => $value).
Try it and you'll see :)
PS: Sorry I didn't notice the inner array, for this case Richard's answer is the correct one. I have added a credit to his answer for giving a correct answer.
So I figured out that I only need 1 foreach loop like so -
foreach($csv as $car){
$type = $car[0];
$echo $type;
}
Works now and thanks all for the help!

foreach () Error

I'm getting the following warning when running this script:
Warning: Invalid argument supplied for foreach()
This is the script:
$values = array();
foreach ($_POST['rights'] as $right_id)
{
$values[] = '(' . $id . ', ' . $right_id . ')';
}
$_POST['rights']/$id are integers. In this case it was $_POST['rights'] = 1,2,3,4,5; $id = 2.
The strange part is that on a different page with the same kind of input it gives no errors.
The question: What is wrong with it?
check $_POST['rights']
var_dump($_POST['rights']);
I think $_POST['rights'] is not an array.
foreach must take an array, you're passing it an integer. You can't iterate over an integer.
A wise move might be to check whatever you're about to iterate over is indeed an array:
if(is_array($_POST['rights'])){
foreach($_POST['rights'] as $value){
//Whatever you want to do with each $value
}
}
else {
//Let the user know it's hit the fan…
throw new Exception('Help, I\'m not an array :(')
}
PHP docs for arrays: http://php.net/manual/en/language.types.array.php
PHP docs for foreach: http://php.net/manual/en/control-structures.foreach.php
As per your statement $_POST['rights'] is not an array.
It is probably a simple string having 1,2,3,4
You need to convert it into an array with explode function.
e.g
$_POST['rights'] = explode(",", $_POST['rights']);
Then your for loop will work.
The passed array $_POST['rights'] probably is empty.
EDIT:
Like Mark Baker said an empty array is fine. You should go with the other answers.

How to get specific instance in PHP array?

I am trying to get the specific value of file extension in this array. All I can do so far is .
I am wanting the fileextention ".jpg"
All I know how to do is echo the values like so using foreach;
file_nameBob7213.jpg file_typeimage/jpeg
file_pathC:/xampp/htdocs/midas/records/
full_pathC:/xampp/htdocs/midas/records/Bob7213.jpg raw_nameBob7213
orig_nameBob72.jpg client_nameafasfafs.jpg **file_ext.jpg** file_size44.96
is_image1 image_width716 image_height474 image_typejpeg
image_size_strwidth="716" height="474"
I am only interested in retrieving the file_ext from this array. How do I select that exact thing?
foreach ($file['upload_data'] as $item => $value)
{
echo $item; echo $value; echo "<br/>";
}
How do I do this? , thanks!
$file['upload_data']['file_ext']
It's just an array within an array, so specify 2 array keys
Incidentally, if you want to see the contents of an array, a quick way of doing it is to use var_export:
var_export($file); # echoes the entire array
You don't need to write a foreach loop every time
$file['upload_data']['file_ext'] contains '.jpg'.

PHP, problem with str_replace while reading from array

i am new to php, and i am trying to do a script that reads an CSV file(file1.csv) and compare the words in the file with words in a html file (file2.html), if word in file2.html match with the key part in file1.csv it should change the file2.html contents with the value of the key matched ..
what i have done so far is this :
$glossArray = array();
$file_handle = fopen("file1.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 10000,';');
$glossArray[$line_of_text[0]] = $line_of_text[1];
$counter++;
}
fclose($file_handle);
$file = file_get_contents("file2.html");
foreach($glossArray as $key => $value){
$results = str_replace($key," means ".$value ,$file);
}
echo $results;
i think that my problem occurs when i try to iterate and change values .. because what i see is only the contents of file2.html unchanged
any help would be appreciated
thank you in advance
Nader
P.s. i edited the old code with the new one after your valuable advise .. now it's like this .. but still doesnt work.
Update: changing the foreach with :
$results = str_replace(array_keys($glossArray), "means ".array_values($glossArray), $file);
solved the problem .. but another one comes up: now every time it replaces a string it adds the word 'Array' ahead of it.
You're passing the entire $glossArray in to str_replace each time. You're also passing the initial file contents in each time you do str_replace, so at most you'd see one replacement. I think you want to change to something like this:
$results = $file;
foreach($glossArray as $index=>$value)
{
$results = str_replace($index,$value ,$results);
}
Since str_replace allows arrays for the first two parameters (as another user mentions) you could also do something like this instead of a loop:
$results = str_replace(array_keys($glossArray), array_values($glossArray), $file);
Yes, the problem is in your second foreach. It should read like this:
foreach($glossArray as $key => $value){
$results = str_replace($key,$value ,$file);
}
You forgot the key, so it's replacing every instance of every value in $glossArray with the $value. Good luck with that!
Why are you opening file2.html for reading and writing, then grabbing the contents of it?
(BTW - this is going to go horribly wrong on a system with strict locking)
foreach($glossArray as $value)
{
$results = str_replace($glossArray,$value ,$file);
I think this should be
foreach($glossArray as $old=>$new)
{
$results = str_replace($old, $new, $file);
Although it would be a lot more efficient to load the pairs from the glossary into 2 seperate numbered arrays, then just call str_replace once.
Your first parameter for str_replace should not be $glossArray as that's an array and not the string to replace.
I assume that your CSV-file contains something like "SEARCH;REPLACE"? In that case, your foreach should look like this: foreach ($glossArray as $searchString => $value).
Then try
$file = str_replace($searchString, $value ,$file);
instead of
$results = str_replace($searchString, $value ,$file);
because right now you're overwriting $results again and again with every str_replace ... echo $file when you're done.
BTW: What's $counter doing?
The solution to your new problem (which should really be it's own question, not an edit of the existing one) is that array_values returns an array, and when you concatenate an array with a string, php inserts 'Array' instead of the value.
$results = str_replace(array_keys($glossArray), "means ".array_values($glossArray), $file);
is incorrect. You should do this instead:
$vals = array_values($glossArray);
foreach($vals as $k=>$v)$vals[$k] = 'means '.$v;
$results = str_replace(array_keys($glossArray), $vals, $file);
Notice that the values of glossArray are extracted, and each value concatenated with your string - if you just try and concatenate the string with the array, you'll get a string, not an aray.

Categories