In_array not working - compare two files - php

The code below is a simple version of what I am trying to do. The code will read in two files, see if there is a matching entry and, if there is, display the difference in the numbers for that item. But it isn't working. The first echo displays the word but the second echo is never reached. Would someone please explain what I am missing?
$mainArry = array('Albert,8');
$arry = array('Albert,12');
foreach ($arry as $line) {
$kword = explode(',', $line);
echo 'kword '.$kword[0];
if (in_array($kword[0], $mainArry)) {
echo 'line '.$line. ' has count of '.$kword[1] . '<br>';
}
}

Your $mainArry contains a single element: the string 'Albert,8'. It looks like you want to use it as an array (elements 'Albert' and '8') instead of a string.
You mention the code will read from two files, so you can 'explode' it to a real array, as you do with $arry. A simpler approach would be using str_getcsv() to parse the CSV string into $mainArry.
$inputString = 'Albert,8';
$mainArry = str_getcsv($inputString); // now $mainArry is ['Albert','8']
$arry = array('Albert,12');
foreach ($arry as $line) {
$kword = explode(',', $line);
echo 'kword '.$kword[0];
if (in_array($kword[0], $mainArry)) {
echo 'line '.$line. ' has count of '.$kword[1] . '<br>';
}
}
Test it here.

You are attempting to compare the string Albert with Albert,8, so they won't match. If you want to check if the string contains the keyword, assuming your array has more than one element, you could use:
$mainArry = array('Albert,8');
$arry = array('Albert,12');
foreach ($arry as $line) {
$kword = explode(',', $line);
echo 'kword '.$kword[0];
foreach ($mainArry as $comp) {
if (strstr($comp, $kword[0])) {
echo 'line '.$line. ' has count of '.$kword[1] . '<br>';
}
}
}
example: https://eval.in/728566

I don't recommend your way of working, but this is a solution, basically the process you apply to the $arry should also apply to the $mainArry you're trying to compare it to.
$mainArry = array('Albert,8');
$arry = array('Albert,12');
/***
NEW function below takes the valus out of the main array.
and sets them in their own array so they can be properly compared.
***/
foreach ($mainArry as $arrr){
$ma = explode(",",$arrr);
$names[] = $ma[0];
$values[] = $ma[1];
}
unset($arrr,$ma);
foreach ($arry as $line) {
$kword = explode(',', $line);
echo 'kword '.$kword[0];
/// note var reference here is updated.
if (in_array($kword[0], $names)) {
echo '<br>line '.$kword[0]. ' has count of '.$kword[1] . '<br>';
}
}
Yeah, MarcM's answer above does the same thing in a neat single line, but I wanted to illustrate a little more under the hood operations of the value setting. :-/

Related

Array seems empty with Implode on array_values

Some assistance would be greatly appreciated:
The 'foreach' section works perfectly and echo's the result set perfectly; as soon as I try the implode it fails? Thank you!
$ctr = 0;
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$RespondentsResultSetArray[$ctr] = array(
"Firstname" => $row['cnt_firstname'],
"Lastname" => $row['cnt_lastname']
);
$ctr = $ctr + 1;
}
foreach ($RespondentsResultSetArray as $key) {
echo $key["Firstname"] . ' ' . $key["Lastname"] . ', ';
}
sqlsrv_free_stmt($stmt);
echo implode(', ',array_values($RespondentsResultSetArray));
try this
implode(',',$RespondentsResultSetArray);
You are passing an array of arrays to implode function. Here is a little deviation of your code, that should get you to the same result:
$full_array = array();
foreach ($RespondentsResultSetArray as $key) {
echo $key["Firstname"] . ' ' . $key["Lastname"] . ', ';
array_push($full_array,$key["Firstname"]);
array_push($full_array,$key["Lastname"]);
}
echo implode(', ',$full_array);
Also, for the future, try to chose smaller names for your variables, and use lowercase for your variable names and array index.
The php implode function accepts an array of strings.
You are not passing it an array of strings.
To user1844933 that just answered, your suggestion would pass implode an array of arrays. That won't work for the same reason.
$RespondentsResultSetArray=array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
array_push($RespondentsResultSetArray,$row['cnt_firstname'].' '.$row['cnt_lastname']);
}
$saved_to_variable=implode(', '$RespondentsResultSetArray);
Will create an array of strings which you can then implode
Since you recently commented that you want to save it to a variable rather than echo it, I just changed the last line of the example code. I believe that will give you the properly spaced, and delimited string that you desire.
since$RespondentsResultSetArray is multidimensional array use foreach loop before echo
$string = "";
foreach($RespondentsResultSetArray as $values)
{
echo implode(array_values($values),",");
$string= $string.",".implode(array_values($values),",");
}
$string=ltrim($string,",");
echo $string;
Demo

How can I echo specific line from a text area using php

I am collecting html text area data to echo in php.I am able to select all data using
$devices = explode("\n", $_POST['devs']);
foreach($devices as $device)
echo $device;
and I am able to select only the first line using:
$first_line = strstr(($_POST['devs']), "\n", true);
echo $first_line;
But How can I echo specific lines ? say line 2 or 4 from text area ?
Usage:
getLines(YOUR POST, START LINE, END LINE(optional));
With return array:
function getLines($text, $start, $end = false)
{
$devices = explode("\n", $text);
$append = "My device is ";
$output = array();
foreach ($devices as $key => $line)
{
if ($key+1 < $start) continue;
if ($end && $key+1 > $end) break;
$output[] = $append.$line;
}
return $output;
}
$array = getLines($_POST['devs'], 2);
var_dump($array);
With echo string:
function getLines($text, $start, $end = false)
{
$devices = explode("\n", $text);
$append = "My device is ";
$output = "";
foreach ($devices as $key => $line)
{
if ($key+1 < $start) continue;
if ($end && $key+1 > $end) break;
$output .= $append.$line."<br />";
}
return $output;
}
echo getLines($_POST['devs'], 2);
Your first code snippet is already creating an array of lines via the explode function.
As such, to output the 2nd and 4th lines, you can simply use:
$devices = explode("\n", $_POST['devs']);
echo $devices[1];
echo $devices[3];
If you're new to PHP (I'm guessing this is the case due to the nature of your question), it should be noted that like many programming languages, arrays are indexed from zero, hence line 2 is 1, line 4 is [3], etc.
UPDATE
To access the penultimate (i.e.: 2nd to last) line, you could use:
echo $devices[count($devices) - 2];
What we're doing here is getting the number of elements in the array (via count) and then subtracting two to fetch the second last element. (As we need to subtract one to deal with the fact that arrays are indexed from zero.)
Do it like this
$nth_line = explode("\n", $_POST['devs'])[n];
where n is you line no.
the explode() returns an array then you can select each element by basic array operation
further readings http://php.net/manual/en/function.explode.php
because $devices is an array after exploding it, you can treat each line by it's index. Reminder that arrays are zero-index based so 1 starts at 0.
$devices = explode('\n', $_POST['devs']);
// line 1
echo $devices[0];
// line 2
echo $devices[1];
// line 4
echo $devices[3];
you can use split:
$lines = split("\n", $_POST['devs']);
echo $lines[3]; //4th line
See documentation http://php.net/manual/es/function.split.php
Take a look at array operations in PHP. Since $devices is an array you can select an element by its index like this: $devices[1] for second element, $devices[2] for third etc.
Lookup your syntax on php.net. It is
$devices = explode(";", "aap;noot;mies");
print_r($devices);
foreach ($devices as $key => $value) {
echo "<br>nr.$key=" . $devices[$key];
}

Php foreach - separating each loop with comma except the last element

Heres what i mean:
foreach ($array as $a) {
echo $a.',<br/>';
}
current output would be:
a,
a,
a,
a,
i want the output to be like this:
a,
a,
a,
a
(all 'a' separated with comma and when it comes to the last loop it doesnt write a comma)
Try this:
echo implode(",<br/>", $array);
If the length of array is too large or you have multidimensional array use the below code
<?php $len=count($array);
foreach($array as $a){
echo $a;
if( $len > 1) echo ',';
$len--;
} ?>
If you'd also like to convert any newlines in the array to <br />, which might be ideal if you're outputting:
echo nl2br(implode(',' . PHP_EOL, $array));
PHP has the implode function for that:
implode(",<br>", $array);
Nobody said you can make it this way:
foreach($array as $element) {
$separator = ($element != end($array)) ? ",<br />" : '';
// or $separator = ($element == end($array)) ? '' : ",<br />";
echo $element.$separator;
}
I suppose this is going to output exactly what you wish.
You should use implode except for one situation.
If the output is huge, and you don't want to keep it in memory before sending to the output (e.g. itemwise processing) then you should do something like:
$remain=count($array);
foreach ($array as $a) {
echo $a;
if($remain-->0) echo ',';
echo '<br/>';
}

Foreach loop, but for first key do something else

Sorry if this is confusing. It's tough for me to put into words having beginner knowledge of PHP.
I'm using the following foreach loop:
foreach ($_POST['technologies'] as $technologies){
echo ", " . $technologies;
}
Which produces:
, First, Second, Third
What I want:
First, Second, Third
All I need is for the loop to skip the echo ", " for the first key. How can I accomplish that?
You can pull out the indices of each array item using => and not print a comma for the first item:
foreach ($_POST['technologies'] as $i => $technologies) {
if ($i > 0) {
echo ", ";
}
echo $technologies;
}
Or, even easier, you can use implode($glue, $pieces), which "returns a string containing a string representation of all the array elements in the same order, with the glue string between each element":
echo implode(", ", $_POST['technologies']);
For general case of doing something in every but first iteration of foreach loop:
$first = true;
foreach ($_POST['technologies'] as $technologies){
if(!$first) {
echo ", ";
} else {
$first = false;
}
echo $technologies;
}
but implode() is best way to deal with this specific problem of yours:
echo implode(", ", $_POST['technologies']);
You need some kind of a flag:
$i = 1;
foreach ($_POST['technologies'] as $technologies){
if($i > 1){
echo ", " . $technologies;
} else {
echo $technologies;
}
$i++;
}
Adding an answer that deals with all types of arrays using whatever the first key of the array is:
# get the first key in array using the current iteration of array_keys (a.k.a first)
$firstKey = current(array_keys($array));
foreach ($array as $key => $value)
{
# if current $key !== $firstKey, prepend the ,
echo ($key !== $firstKey ? ', ' : ''). $value;
}
demo
Why don't you simply use PHP builtin function implode() to do this more easily and with less code?
Like this:
<?php
$a = ["first","second","third"];
echo implode($a, ", ");
So as per your case, simply do this:
echo implode($_POST['technologies'], ", ");

php only get the first occurrence of a word from an array

I have an array of tags that I'm pulling from a database, I am exporting the tags out into a tag cloud. I'm stuck on getting only the first instance of the word. For example:
$string = "test,test,tag,tag2,tag3";
$getTags = explode("," , $string);
foreach ($getTags as $tag ){
echo($tag);
}
This would output the test tag twice. at first i thought i could use stristr to do something like:
foreach ($getTags as $tag ){
$tag= stristr($tag , $tag);
echo($tag);
}
This is obviously silly logic and doesn't work, stristr seems to only replace the first occurrence so something like "test 123" would only get rid of the "test" and would return "123" I've seen this can also be done with regex but I haven't found a dynamic exmaple of that.
Thanks,
Brooke
Edit: unique_array() works if I'm using a static string but won't work with the data from the database because I'm using a while loop to get each rows data.
$getTag_data = mysql_query("SELECT tags FROM `news_data`");
if ($getTag_data)
{
while ($rowTags = mysql_fetch_assoc($getTag_data))
{
$getTags = array_unique(explode("," , $rowTags['tags']));
foreach ($getTags as $tag ){
echo ($tag);
}
}
}
use array_unique()
$string = "test,test,tag,tag2,tag3";
$getTags = array_unique(explode("," , $string));
foreach ($getTags as $tag ){
echo($tag);
}
Use your words as keys to the dictionary, not as values.
$allWords=array()
foreach(explode("," , $string) as $word)
$allWords[$word]=true;
//now you can extract these keys to a regular array if you want to
$allWords=array_keys($allWords);
While you are at it, you can also count them!
$wordCounters=array()
foreach(explode("," , $string) as $word)
{
if (array_key_exists($word,$wordCounters))
$wordCounters[$word]++;
else
$wordCounters=1;
}
//word list:
$wordList=array_keys($wordCounters);
//counter for some word:
echo $wordCounters['test'];
I'm assuming that each row in your table contains more than one tag, separated by coma, like this:
Row0: php, regex, stackoverflow
Row1: php, variables, scope
Row2: c#, regex
If that's the case, try this:
$getTag_data = mysql_query("SELECT tags FROM `news_data`");
//fetch all the tags you found and place it into an array (with duplicated entries)
$getTags = array();
if ($getTag_data) {
while ($row = mysql_fetch_assoc($getTag_data)) {
array_merge($getTags, explode("," , $row['tags']);
}
}
//clean up duplicity
$getTags = array_unique($getTags);
//display
foreach ($getTags as $tag ) {
echo ($tag);
}
I'd point out that this is not efficient.
Another option (already mentioned here) would be to use the tags as array keys, with the advantage of being able to count them easily.
You could do it like this:
$getTag_data = mysql_query("SELECT tags FROM `news_data`");
$getTags = array();
if ($getTag_data) {
while ($row = mysql_fetch_assoc($getTag_data)) {
$tags = explode("," , $row['tags']);
foreach($tags as $t) {
$getTags[$t] = isset($getTags[$t]) ? $getTags[$t]+1 : 1;
}
}
}
//display
foreach ($getTags as $tag => $count) {
echo "$tag ($count times)";
}
please keep in mind none of this code was tested, it's just so you get the idea.
I believe php's array_unique is what you are looking for:
http://php.net/manual/en/function.array-unique.php
Use the array_unique function before iterating over the array? It removes every duplicate string and return the unique functions.

Categories