I need server to return complete IDs that contain an integer(single digit or more) sent in by a user to find a match.
e.g I submit '5678', then server returns 12567891, 54356782, 90567811.
Emphasis on '5678'. My code returns no results.
<?php
$per = array(456755643, 78567561, 443321, 33267554560, 44321122, 554367533, 3390);
$thr = 675;
if(isset($_POST['search'])){
$jake = preg_grep(("/$thr+/", $per);
foreach($jake as $value){
print $value . br;
}
}
?>
try this
$per = array(456755643, 78567561, 443321, 33267554560, 44321122, 554367533, 3390);
$thr = 675;
$jake = preg_grep("/$thr/", $per);
foreach($jake as $value){
print $value . '<br>';
}
//result
456755643
78567561
33267554560
554367533
Related
I am trying to check if a number say 1 is present in a string say 11,12,13 To do this I am using strpos:
<?
$s = "2,3,11,12,13";
$ss = "1";
if(strpos($s, $ss)) echo "success";
else echo "fail";
?>
Here I am expecting the code to give fail as output but it gives success.
Is there any function I can use to exactly match the number in a string. I want the number 1 in the string, not the numbers containing 1 like 11,123,100 etc.
Edit 1: It works fine for #Twinfriends answer but the problem is doing it with multiple numbers.
<?
$s = "2,3,11,12,13";
$ss = "1,2";
if(strpos($s, $ss)) echo "success";
else echo "fail";
?>
This code gives output fail but it should give true.
Edit 2: Check answer https://stackoverflow.com/a/48297002/8490014
The problem has been solved but because of for each loop the output is getting repeated as many times as there are values in the array. How can we get the output repeating the output?
You could do it like this:
<?php
$s = "2,3,11,12,13";
$ss = "1";
$toTest = explode(",", $s);
if(in_array("$ss", $toTest)) {
echo "success";
}
else {
echo "fail";
}
?>
If you've any question considering this code, feel free to ask. (Code tested, works well)
The problem has been solved by adding a foreach loop:
<?
$s = "2,3,11,12,13";
$ss = "1,2,3,5";
$catid = explode(",", $s);
$ocat = explode(",",$ss);
foreach($ocat as $abc) {
if(in_array($abc, $catid)) {
echo "success";
}
else {
echo "fail";
}
}
?>
Try this:
<?php
$s = "2,3,11,12,13";
$ss = "1";
$haystack = explode(",",$s);
$matches = preg_grep ("/$ss/", $haystack);
echo !empty($matches) ? "success" : "fail";
You can check by appending comma after the variable to check occurrence at start, appending comma before the variable to check occurrence at last or appending comma before and after the variable to check occurrence at middle.
if((substr($s, 0, (strlen($ss)+1)) === $ss.',')||(substr($s, (strlen($s)-strlen($ss)-1), strlen($s)) === ','.$ss)||(strpos($s, ','.$ss.','))){
echo "success";
}
else{
echo "fail";
}
I have just learnt some basic skill for html and php and I hope someone could help me .
I had created a html file(a.html) with a form which allow students to input their name, student id, class, and class number .
Then, I created a php file(a.php) to saved the information from a.html into the info.txt file in the following format:
name1,id1,classA,1
name2,id2,classB,24
name3,id3,classA,15
and so on (The above part have been completed with no problem) .
After that I have created another html file(b.html), which require user to enter their name and id in the form.
For example, if the user input name2 and id2 in the form, then the php file(b.php) will print the result:
Class: classB
Class Number: 24
I have no idea on how to match both name and id at the same time in the txt file and return the result in b.php
example data:
name1,id1,classA,1
name2,id2,classB,24
name3,id3,classA,15
<?php
$name2 = $_POST['name2'];
$id2 = $_POST['id2'];
$data = file_get_contents('info.txt');
if($name2!='')
$konum = strpos($data, $name2);
elseif($id2!='')
$konum = strpos($data, $id2);
if($konum!==false){
$end = strpos($data, "\n", $konum);
$start = strrpos($data, "\n", (0-$end));
$row_string = substr($data, $start, ($end - $start));
$row = explode(",",$row_string);
echo 'Class : '.$row[2].'<br />';
echo 'Number : '.$row[3].'<br />';
}
?>
Iterate through lines until you find your match. Example:
<?php
$csv=<<<CSV
John,1,A
Jane,2,B
Joe,3,C
CSV;
$data = array_map('str_getcsv', explode("\n", $csv));
$get_name = function($number, $letter) use ($data) {
foreach($data as $row)
if($row[1] == $number && $row[2] == $letter)
return $row[0];
};
echo $get_name('3', 'C');
Output:
Joe
You could use some simple regex. For example:
<?php
$search_name = (isset($_POST['name'])) ? $_POST['name'] : exit('Name input required.');
$search_id = (isset($_POST['id'])) ? $_POST['id'] : exit('ID input required.');
// First we load the data of info.txt
$data = file_get_contents('info.txt');
// Then we create a array of lines
$lines = preg_split('#\\n#', $data);
// Now we can loop the lines
foreach($lines as $line){
// Now we split the line into parts using the , seperator
$line_parts = preg_split('#\,#', $line);
// $line_parts[0] contains the name, $line_parts[1] contains the id
if($line_parts[0] == $search_name && $line_parts[1] == $search_id){
echo 'Class: '.$line_parts[2].'<br>';
echo 'Class Number: '.$line_parts[3];
// No need to execute the script any further.
break;
}
}
You can run this. I think it is what you need. Also if you use post you can change get to post.
<?php
$name = $_GET['name'];
$id = $_GET['id'];
$students = fopen('info.txt', 'r');
echo "<pre>";
// read each line of the file one by one
while( $student = fgets($students) ) {
// split the file and create an array using the ',' delimiter
$student_attrs = explode(',',$student);
// first element of the array is the user name and second the id
if($student_attrs[0]==$name && $student_attrs[1]==$id){
$result = $student_attrs;
// stop the loop when it is found
break;
}
}
fclose($students);
echo "Class: ".$result[2]."\n";
echo "Class Number: ".$result[3]."\n";
echo "</pre>";
strpos can help you find a match in your file. This script assumes you used line feed characters to separate the lines in your text file, and that each name/id pairing is unique in the file.
if ($_POST) {
$str = $_POST["name"] . "," . $_POST["id"];
$file = file_get_contents("info.txt");
$data = explode("\n", $file);
$result = array();
$length = count($data);
$i = 0;
do {
$match = strpos($data[$i], $str, 0);
if ($match === 0) {
$result = explode(",", $data[$i]);
}
} while (!$result && (++$i < $length));
if ($result) {
print "Class: " . $result[2] . "<br />" . "Class Number: " . $result[3];
} else {
print "Not found";
}
}
I have this string:
[25-03-15, 1236], [26-03-15, 3000], [27-03-15, 3054], [30-03-15, 4000]
I want to get two parts from it as below:
['25-03-15','26-03-15','27-03-15','30-03-2015']
and
[1236,3000,3054,4000]
Please guide me how I can perform this task.
PS: I am working of view page of codeigniter.
I'm getting the first thing as:
<?php
$usd=$this->db->query('select transaction_date, SUM(amount) as total
from transactions GROUP BY transaction_date')->result_array();
$str = '';
for($i=0; $i<count($usd); $i++){
if($i!=0){
$str = $str.', ['.date('d-m-y', strtotime($usd[$i]["transaction_date"])).', '.$usd[$i]["total"].']';
}else{
$str = $str.'['.date('d-m-y', strtotime($usd[$i]["transaction_date"])).', '.$usd[$i]["total"].']';
}
}
echo $str;
?>
Try this..
$date = '';
$total = '';
for($i=0; $i<count($usd); $i++){
if($i!=0){
$date .= date('d-m-y', strtotime($usd[$i]["transaction_date"])).', ';
$total .= $usd[$i]["total"].', ';
}else{
$date .= date('d-m-y', strtotime($usd[$i]["transaction_date"])).', ';
$total .= $usd[$i]["total"].', ';
}
}
echo $finaldate='['. $date.']';
echo $finaltotal='['. $total.']';
I don't see any reason why you need to save this data from your db in a string. Just save it in an array and it is that easy:
So here I save your data in an array, so that you get this structure:
array(
array(25-03-15, 1236),
array(26-03-15, 3000),
array(27-03-15, 3054),
array(30-03-15, 4000)
)
The you can simply use array_column() to extract the single columns, like this:
<?php
$usd = $this->db->query('select transaction_date, SUM(amount) as total
from transactions GROUP BY transaction_date')->result_array();
foreach($usd as $k => $v)
$result[] = [date('d-m-y', strtotime($usd[$k]["transaction_date"])), $usd[$k]["total"]];
$partOne = array_column($result, 0);
$partTwo = array_column($result, 1);
?>
Also if you then need this data in a string as you said in the comments you can simply transform it:
I will pass this extracted data to a graph that accepts this kind of data – Shahid Rafiq 6 mins ago
Just use this:
echo $str = "[" . implode("],[", array_map(function($v){
return implode(",", $v);
}, $usd)) . "]";
output:
[25-03-15, 1236], [26-03-15, 3000], [27-03-15, 3054], [30-03-15, 4000]
EDIT:
If you also want the parts as string just simply do this:
$partOne = "[" . implode("],[", array_column($arr, 0)) . "]";
$partTwo = "[" . implode("],[", array_column($arr, 1)) . "]";
output:
[25-03-15],[26-03-15],[27-03-15],[30-03-15]
[1236],[3000],[3054],[4000]
i need to sort some strings and match them with links, this is what i do:
$name_link = $dom->find('div[class=link] strong');
Returns array [0]-[5] containing strings such as NowDownload.eu
$code_link = $dom->find('div[class=link] code');
Returns links that match the names from 0-5, as in link [0] belongs to name [0]
I do not know the order in which they are returned, NowDownload.Eu, could be $code_link[4] or $code_link [3], but the name array will match it in order.
Now, i need $code_link[4] // lets say its NowDownload.Eu to become $link1 every time
so i do this
$i = 0;
while (!empty($code_link[$i]))
SortLinks($name_link, $code_link, $i); // pass all links and names to function, and counter
$i++;
}
function SortLinks($name_link, $code_link, &$i) { // counter is passed by reference since it has to increase after the function
$string = $name_link[$i]->plaintext; // name_link is saved as string
$string = serialize($string); // They are returned in a odd format, not searcheble unless i serialize
if (strpos($string, 'NowDownload.eu')) { // if string contains NowDownload.eu
$link1 = $code_link[$i]->plaintext;
$link1 = html_entity_decode($link1);
return $link1; // return link1
}
elseif (strpos($string, 'Fileswap')) {
$link2 = $code_link[$i]->plaintext;
$link2 = html_entity_decode($link2);
return $link2;
}
elseif (strpos($string, 'Mirrorcreator')) {
$link3 = $code_link[$i]->plaintext;
$link3 = html_entity_decode($link3);
return $link3;
}
elseif (strpos($string, 'Uploaded')) {
$link4 = $code_link[$i]->plaintext;
$link4 = html_entity_decode($link4);
return $link4;
}
elseif (strpos($string, 'Ziddu')) {
$link5 = $code_link[$i]->plaintext;
$link5 = html_entity_decode($link5);
return $link5;
}
elseif (strpos($string, 'ZippyShare')) {
$link6 = $code_link[$i]->plaintext;
$link6 = html_entity_decode($link6);
return $link6;
}
}
echo $link1 . '<br>';
echo $link2 . '<br>';
echo $link3 . '<br>';
echo $link4 . '<br>';
echo $link5 . '<br>';
echo $link6 . '<br>';
die();
I know they it finds the link, i have tested it before, but i wanted to make it a function, and it messed up, is my logic faulty or is there an issue with the way i pass the variables/ararys ?
I don't know why you pass $i as reference since you use it just for reading it. You could return an array contaning the named links and using it like so :
$all_links = SortLinks($name_link,$code_link);
echo $all_links['link1'].'<br/>';
echo $all_links['link2'].'<br/>';
You will have to put your loop inside the function, not outside.
Why not output the first element array?
i use next code
$product_idn='123112$2313213';
$count_products=substr_count($product_idn,'$')+1;
$idn_products=explode('$',$product_idn);
$name_products='';
$s=0;
while($s<=$count_products){
$prod=$idn_products[$s];
$res10=mysql_query("..... WHERE `product_idn`='$prod'");
$i10=mysql_fetch_assoc($res10);
$name_products.=$i10['name'].', ';
$s++;
}
echo $name_products;
//give 2313213,,
Why not output the first element array ?
What about
$product_idn='123112$2313213';
$idn_products=explode('$',$product_idn);
$name_products='';
foreach($idn_products as $val){
$res10=mysql_query("..... WHERE `product_idn`='$val'");
$i10=mysql_fetch_assoc($res10);
$name_products.=$i10['name'].', ';
}
echo $name_products;
There are a lot of unusual techniques being used in the original code. My best guess at what I'd do, without really knowing the purpose of this code is:
$product_idn = '123112$2313213';
$idn_products = explode('$', $product_idn);
$name_products = '';
foreach($product_idn as $value) {
$res10 = mysql_query("SELECT name FROM ... WHERE `product_idn`='$value'");
if ($res10) {
$i10 = mysql_fetch_assoc($res10);
$name_products .= $i10['name'].', ';
}
}
$name_products = rtrim(', ', $name_products);
echo $name_products;