Compare string from input field with value in multidimension array - php

$klasseinput = strtoupper(trim($_POST["klasseliste"]));
$data = file('student.txt');
$data = array_filter($data);
foreach($data AS $row){
$student[] = explode(';', $row);
}
$antall = count($student);
for ($i = 0; $i < $antall; $i++){
if($klasseinput == $student[$i][3]){
print('<tr><td>'.$student[$i][0]."</td><td>".$student[$i][1]."</td><td>".$student[$i][2]."</td><td>".$student[$i][3]."</td></tr>");
}
}
/////////STUDENT.txt//////////
ph;petter;hanssen;IT1
gb;Geir;Bjarvin;IT2
mj;Marius;Johansen;IT3
/////////////////////////////
I am trying to compare an input form with an item in the multidimension array, but even tho the variable from the input field is exactly the same as the value in the array, it doesnt pass the if check.
$student[0][3] = IT1
$student[1][3] = IT2
$student[2][3] = IT3

If you have made sure there is no white space spoiling the comparison, then you might find a function like this useful to look at the strings on both sides of the comparison. You might find there are spurious characters causing trouble.
function hexdump($str)
{
for($i=0; $i<strlen($str);$i++)
{
echo "[$i] [".bin2hex($str[$i])."] [".$str[$i]."]<br />";
}
}
For instance, the string read from the file might contain CR LF characters. You could get rid of them using str_replace().

Thanks to Ravinder Reddy for the answer that was simple and worked for me:
" trim the value for \t\n if($klasseinput == trim($student[$i][3])){ "

Related

php sum the values seperated by special character

I need to sum the result set values separated by "|" inside the loop eg. set of values 10|2, 6|2, 8|1 should result in 24|5.
here is my code:
<?php
$fromdate="2016-03-31";
$todate="2016-03-31";
$TAG="1";
$con = mysqli_connect("XXXXX","XX","XXX","XXX");
$query = mysqli_query($con, "CALL sp_Android_Online_Dashboard('$fromdate', '$todate','$TAG')") or die("Query fail: " . mysqli_error());
$Totfiles = 0;
$file_minutes = 0;
$Tot_minutes=0;
$Pending=0;
while(($row = mysqli_fetch_array($query)))
{
$Totfiles +=$row["Totfiles"];
$file_minutes +=$row["file_minutes"];
$Pending =str_replace(array("/"),"|",$row["Pending"]); //need to sum all the values separated by "|"
$Tot_minutes +=$row["Tot_minutes"];
}
$response["Details"]['Totfiles'] = $Totfiles;
$response["Details"]['file_minutes'] = $file_minutes;
$response["Details"]['Pending'] = $Pending;
$response["Details"]['Tot_minutes'] = $Tot_minutes;
echo json_encode($response);
?>
$row["Pending"] contains the values which are to be summed
result am getting now,
"Pending":"16|9"
"Pending":"11|3"
"Pending":"6|2"
my expected result,
"Pending":"33|14"
This is what you are aiming at i think, you make an array first containing 2 values, on each iteration through the loop you add the new values to them and at the end you can implode it into a string again
// Start with an array containing 0 twice
$Totalpending = [0,0];
while(($row = mysqli_fetch_array($query)))
{
// On each loop we add the left value to the first value in the array and the right value to the second value in the array
$tmp = explode("|", $row['Pending']);
$Totalpending[0] += $tmp[0];
$Totalpending[1] += $tmp[1];
$Totfiles +=$row["Totfiles"];
$file_minutes +=$row["file_minutes"];
$Pending =str_replace(array("/"),"|",$row["Pending"]); //need to sum all the values separated by "|"
$Tot_minutes +=$row["Tot_minutes"];
}
// if you want to format the values in the same way again, although an array is much easier to handle, but it's up to you.
$stringTotalpending = implode('|',$Totalpending);
the string value you want will then be in $stringTotalpending
So Firstly, we need to explode the values from $row["Pending"].
$arr = explode("|", $row["Pending"]);
Now use a loop to add those two numbers:
$temp = 0;
for($i = 0; $i < count($arr); $i++){
$temp += (int) $arr[$i];
}
Now the $temp would contain the result.
As simple as that.
And also as a side note, your code is vulnerable to SQL-Injection attacks.
What about evaling the same string with '|' replaced by '+' ?
eval('$result = ' . str_replace('|', '+', preg_replace('/[^0-9|]/', '', $row["Pending"])) . ';');
echo "$result\n";
Note preg_replace() to sanitize input. Can be avoided if input is already sanitized

Extracting meaningful data from this complicated string in PHP

I'm receiving some structured data for my PHP application, but the format is somewhat unpredictable and difficult to deal with. I don't get a say in the initial format of the data. What I get is a string (sample given below).
[9484,'Víctor Valdés',8,[[['accurate_pass',[15]],['touches',[42]],['saves',[4]],['total_pass',[24]],['good_high_claim',[2]],['formation_place',[1]]]],1,'GK',1,0,0,'GK',31,183,78],[1320,'Carles Puyol',7.76,[[['accurate_pass',[50]],['touches',[75]],['aerial_won',[3]],['total_pass',[55]],['total_tackle',[1]],['formation_place',[6]]]],2,'DC',5,0,0,'D(CLR)',35,178,80],[5780,'Dani Alves',8.21,[[['accurate_pass',[58]],['touches',[99]],['total_scoring_att',[1]],['total_pass',[66]],['total_tackle',[6]],['aerial_lost',[1]],['fouls',[4]],['formation_place',[2]]]],2,'DR',22,0,0,'D(CR)',30,173,64],[83686,'Marc Bartra',8.31,[[['accurate_pass',[64]],['touches',[88]],['won_contest',[1]],['total_scoring_att',[1]],['aerial_won',[1]],['total_pass',[66]],['total_tackle',[5]],['aerial_lost',[1]],['fouls',[1]],['formation_place',[5]]]],2,'DC',15,0,0,'D(C)',22,181,70],[13471,'Adriano',6.72,[[['accurate_pass',[16]],['touches',[28]],['aerial_won',[2]],['total_pass',[18]],['total_tackle',[1]],['formation_place',[3]]]],2,'DL',21,1,31,'D(CLR),M(LR)',29,172,67]
The above is data for 5 football players. This is what I need to get:
[9484,'Víctor Valdés',8,[[['accurate_pass',[15]],['touches',[42]],['saves',[4]],['total_pass',[24]],['good_high_claim',[2]],['formation_place',[1]]]],1,'GK',1,0,0,'GK',31,183,78]
[1320,'Carles Puyol',7.76,[[['accurate_pass',[50]],['touches',[75]],['aerial_won',[3]],['total_pass',[55]],['total_tackle',[1]],['formation_place',[6]]]],2,'DC',5,0,0,'D(CLR)',35,178,80]
[5780,'Dani Alves',8.21,[[['accurate_pass',[58]],['touches',[99]],['total_scoring_att',[1]],['total_pass',[66]],['total_tackle',[6]],['aerial_lost',[1]],['fouls',[4]],['formation_place',[2]]]],2,'DR',22,0,0,'D(CR)',30,173,64]
[83686,'Marc Bartra',8.31,[[['accurate_pass',[64]],['touches',[88]],['won_contest',[1]],['total_scoring_att',[1]],['aerial_won',[1]],['total_pass',[66]],['total_tackle',[5]],['aerial_lost',[1]],['fouls',[1]],['formation_place',[5]]]],2,'DC',15,0,0,'D(C)',22,181,70]
[13471,'Adriano',6.72,[[['accurate_pass',[16]],['touches',[28]],['aerial_won',[2]],['total_pass',[18]],['total_tackle',[1]],['formation_place',[3]]]],2,'DL',21,1,31,'D(CLR),M(LR)',29,172,67]
Now, what I've done manually in the above example I need to do reliably with PHP. As you see, each player has a set of data. In order to split the big string into individual players, I can't just explode it by "],[" because that substring appears within each player's data too an unpredictable number of times.
Each player has a certain number of statistics (accurate_pass, touches etc) but they don't all have the same statistics. For instance, player #1 has "saves" and the others don't. Player #4 has "won_contest" and the others don't. There is no way to know who will have which stats. That means I can't just count commas until the new player or something similar.
Each player has a number before his name, but that number has an unpredictable number of digits and there's no way to discern it from other numbers which may appear in the string.
What I see as a constant occurrence for all players is the last bit: before the last closed bracket there are always 3 integers divided by commas. This type of substring (INT,INT,INT]) doesn't seem to appear in any other situation. Maybe this could be of some use?
A "hard" way to do this is parenthesis counting (less common in PHP, more common in text parsing languages)...
<?php
$str = "[9484,'Víctor Valdés',8,[[['accurate_pass',[15]],['touches',[42]],['saves',[4]],['total_pass',[24]],['good_high_claim',[2]],['formation_place',[1]]]],1,'GK',1,0,0,'GK',31,183,78],[1320,'Carles Puyol',7.76,[[['accurate_pass',[50]],['touches',[75]],['aerial_won',[3]],['total_pass',[55]],['total_tackle',[1]],['formation_place',[6]]]],2,'DC',5,0,0,'D(CLR)',35,178,80],[5780,'Dani Alves',8.21,[[['accurate_pass',[58]],['touches',[99]],['total_scoring_att',[1]],['total_pass',[66]],['total_tackle',[6]],['aerial_lost',[1]],['fouls',[4]],['formation_place',[2]]]],2,'DR',22,0,0,'D(CR)',30,173,64],[83686,'Marc Bartra',8.31,[[['accurate_pass',[64]],['touches',[88]],['won_contest',[1]],['total_scoring_att',[1]],['aerial_won',[1]],['total_pass',[66]],['total_tackle',[5]],['aerial_lost',[1]],['fouls',[1]],['formation_place',[5]]]],2,'DC',15,0,0,'D(C)',22,181,70],[13471,'Adriano',6.72,[[['accurate_pass',[16]],['touches',[28]],['aerial_won',[2]],['total_pass',[18]],['total_tackle',[1]],['formation_place',[3]]]],2,'DL',21,1,31,'D(CLR),M(LR)',29,172,67]";
$line = ',';
$paren_count = 0;
$lines = array();
for($i=0; $i<strlen($str); $i++)
{
$line.= $str{$i};
if($str{$i} == '[') $paren_count++;
elseif($str{$i} == ']')
{
$paren_count--;
if($paren_count == 0)
{
$lines[] = substr($line,1);
$line = '';
}
}
}
print_r($lines);
?>
Looks like #Boundless answer is correct, you can use json_decode, but you need to do a couple of things to the string you get first, which also seems like a valid json formatted string.
This worked for me:
<?php
$str = "[9484,'Víctor Valdés',8,[[['accurate_pass',[15]],['touches',[42]],['saves',[4]],['total_pass',[24]],['good_high_claim',[2]],['formation_place',[1]]]],1,'GK',1,0,0,'GK',31,183,78],[1320,'Carles Puyol',7.76,[[['accurate_pass',[50]],['touches',[75]],['aerial_won',[3]],['total_pass',[55]],['total_tackle',[1]],['formation_place',[6]]]],2,'DC',5,0,0,'D(CLR)',35,178,80],[5780,'Dani Alves',8.21,[[['accurate_pass',[58]],['touches',[99]],['total_scoring_att',[1]],['total_pass',[66]],['total_tackle',[6]],['aerial_lost',[1]],['fouls',[4]],['formation_place',[2]]]],2,'DR',22,0,0,'D(CR)',30,173,64],[83686,'Marc Bartra',8.31,[[['accurate_pass',[64]],['touches',[88]],['won_contest',[1]],['total_scoring_att',[1]],['aerial_won',[1]],['total_pass',[66]],['total_tackle',[5]],['aerial_lost',[1]],['fouls',[1]],['formation_place',[5]]]],2,'DC',15,0,0,'D(C)',22,181,70],[13471,'Adriano',6.72,[[['accurate_pass',[16]],['touches',[28]],['aerial_won',[2]],['total_pass',[18]],['total_tackle',[1]],['formation_place',[3]]]],2,'DL',21,1,31,'D(CLR),M(LR)',29,172,67]";
$str = '[' . $str . ']';
$str = str_replace('\'','"', $str);
//convert string to array
$arr = json_decode($str);
//now it's a php array so you can access any value
//echo '<pre>';
//print_r( $arr );
//echo '</pre>';
echo $arr [0][1]; //prints "Victor Valdes"
?>
Your string looks like JSON but it is not valid JSON so json_decode() will not work.
Your specific case could be converted to valid JSON by wrapping the string in a pair of [] and replacing the single quotes with double quotes:
$string = str_replace("'", '"', $your_string);
var_dump(json_decode('[' . $string . ']'));
See this example.
Of course the best solution would be to make sure that valid JSON is supplied because this will break easily if your text strings contain for example double quotes.
Try parsing as json, then pulling out what you want. Assuming that the data comes in blocks of 4 you can try:
$arr = json_decode($str);
for($i = 0; $i < count($arr) - 3; $i += 4)
{
$arr[] = new array($arr[$i], $arr[$i + 1], $arr[$i + 2], $arr[$i + 3]);
}
Why not count the [ in a loop? Here's a quick untested loop that could get you started.
$output = array('');
$brackets = 0;
$index = 0;
foreach (str_split($input) as $ch) {
if ($ch == '[') {
$brackets++;
}
$output[$index] .= $ch;
if ($ch == ']') {
$brackets--;
if ($brackets === 0) {
$index++;
$output[$index] = '';
}
}
}
Not very elegant though...

php reading in strings from text area

$data = explode("\n", trim($_GET['names']));
while($i < count($data)) {
if(!in_array($data[$i], $unique_names)){
$unique_names[] = $names[$i];
}
$i = $i + 1;
}
I am trying to accept only unique results from a textarea using this php code. It is not working because every string has an extra blank space, except for the last one.
I.E.
"jeff "
"fred "
"bill "
"jeff"
so jeff will be added twice.
My question is:
How Do I get rid of that space?? I tried trim and it won't perform as intended.
First of all, you don't need to find unique values manually, you can use array_unique(). Secondly, trim() doesn't work on arrays.
Try:
$raw_names = explode("\n", $_GET['names']);
$trimmed_names = array_map('trim', $raw_names);
$unique_names = array_unique($trimmed_names);
Use trim(string) to remove whitespace from the start and end. http://php.net/manual/en/function.trim.php
Inspired by kba :
$data = explode("\n", trim($_GET['names']));
foreach ($data as &$e) {
$e = trim($e);
}
$unique_names = array_unique($data);

possible limitation of implode function in PHP

I have the following code that is not returning as I expected. I was hoping the final result would be a string:
$organizers = array_unique($organizers); // this returns correctly
$organizers = implode(', ', $organizers); // this returns nothing
var_dump($organizers); // no data appears here
exit;
The array_unique() function is returning data correctly and I can see the array it returns. To start, the $organizers array is a simple 1-D array of strings that all have small lengths under 20 chars. I think the issue might be that $organizers is more than 10,000 indices long. Are there limitations on the length of an array that can be imploded? Are there work-arounds for that? I cannot find anything in the manual, but I have tested this code thoroughly and I believe the error must be on implode().
I dont' know if there is a limitation, but what comes to my mind is taht you are also transforming an array into a string. This shouldn't be the problem in PHP, but try calling it a different variable for the result of implode?
$organizers = array_unique($organizers); // this returns correctly
$organizers_string = implode(', ', $organizers); // this returns nothing
// This gives it a different space
Edit: And if for some reason implode() is still problematic.
$organizers = array_unique($organizers);
$neworganizers = "";
for($i = 0; $i < sizeof($organizers); $i++)
{
$neworganizers .= $organizers[$i];
if($i != sizeof($organizers) - 1)
{
$neworganizers .= ", ";
}
}
//$neworganizers is now the equivalent of what .implode() should return when called on $organizers
$organizers = array();
$organizers[0] = "value1";
$organizers[1] = "value2";
$organizers[2] = "value3";
$organizers[3] = "value3";
$organizers = array_unique($organizers); // strips out last index
$organizers = implode(', ', $organizers); // returns string of "value1, value2, value3"
echo $organizers;
This seemed to work on writecodeline.com/php/
I've also experienced issues with older php builds when I've tried to explode/implode by a string with special characters in it and they were encapsulated by single quotes. I know it sounds crazy, but the double quotes might be necessary on some servers.
Reference: personal experience doing work on older production servers.
I'd hate to think I'm stating the obvious, but doesn't implode only take a string as an argument? Maybe it should be something more like this...
$organizers = array_unique($organizers);
//I'm guessing what you wanted was an array of arrays?
$neworganizers = array();
for($i = 0; $i < sizeof($organizers); $i++)
{
$neworganizers[$i] = implode(", ", $organizers);
}
print_r($neworganizers);

No Output? PHP foreach doesn't seem to work

I am trying to form an acronym from a given text. The Idea here is that the first Letter in $text ($text[0]) will be taken and placed inside the array $storage using array_push(). Now, if there is a space inside the array, the letter of the next index should be a part of the Acronym. I am currently not getting an ouput, what am I missing?
public function Acronym($text)
{
$text = str_split($text);
$count = strlen($text);
$storage = array();
for($i=0; $i<$count; $i++)
{
array_push($storage, $text[0]);
if($text[$i]==' ')
{
array_push($storage, $text[$i+1]);
}
foreach($storage as $clean)
{
echo $clean;
}
}
}
Your algorithm suffers from a few fatal flaws:
You're calling strlen() on an array, when you should be calling count():
$text = str_split($text);
$count = count($text);
However, you can index strings as arrays, so you don't need str_split() in this scenario, and you can keep $count = strlen( $text); by removing the call to str_split().
This should only happen once, so it should be outside the loop (This implies starting $i at 1):
array_push($storage, $text[0]);
Your foreach loop that prints the $storage array should be outside of the loop that is creating the acronym.
You can save the overhead of calling a function by using the shorthand array_push() notation. You should use array_push() when adding more than one element to an array. Otherwise, this will suffice:
$storage[] = $text[0];
You need to return something from your function, otherwise you won't be able to access anything outside of it.
Put that all together, and you get this:
public function Acronym($text)
{
$count = strlen( $text);
$storage[] = $text[0];
for( $i = 1; $i < $count; $i++)
{
if( $text[$i] == ' ')
{
$storage[] = $text[$i+1]);
$i++; // Can increment $i here because we know the next character isn't a space
}
}
foreach($storage as $clean)
{
echo $clean;
}
return $storage;
}
That being said, there are far better implementations for forming an acronym giving a string input. Here is one that I can think of:
public function Acronym( $text)
{
$acronym = array();
foreach( explode( ' ', $text) as $word)
{
$word = trim( $word);
$acronym[] = strtoupper( $word[0]);
}
return implode( '', $acronym);
}
Note that both functions will fail for inputs like Hello World. I am leaving it up to the OP to make these modifications (if necessary).
str_split turns the string into an array.
str_length brings the length of a string which you have overwritten with an array already. you need count()
You overwrite your first variable $text
$count = strlen($text);
In this line $text is an array, because you changed it in the first line of your method.
Try inverting the two first lines:
$count = strlen($text);
$text = str_split($text);
Note
This will solve your secondary problem, and enable your algorithm to run without errors. It doesn't fix your algorithm, but at least you will be able to debug it now.
you are running your loop on $count which is getting its value from str_len its an array because of return on $text = str_split($text);
So you have overwritten your $text variable you can fix it by changing order get length first then split.

Categories