When I get vars from an url I make a string. But the string must be different if the var exists or not on url. Here's an example:
I have two urls:
www.domain.com/list.php?cli=paris&resp=James&type=emp
www.domain.com/list.php?type=emp
I can get vars from first url with $_GET
$var = "HAVING ".$_GET['cli']." AND ".$_GET['resp']." AND ".$_GET['type'];
and
$var = "HAVING paris and James and emp"
but on the second url I have $var="HAVING AND AND emp" because the first and the second vars are empty.
I can use multiple conditions for all of the vars (url can have 5 or 6 vars), but I think that there is a better solution.
Thanks
This should work for you:
(Just use implode() and you don't have to check anything)
echo $var = "HAVING " . implode(" AND ", $_GET);
Output:
HAVING paris AND James AND emp
HAVING emp
EDIT:
From your comment, this should work for you:
<?php
$str = "HAVING ";
$sep = "";
foreach($_GET as $k => $v) {
$str .= "$sep $k='$v'";
$sep = " AND ";
}
echo $str;
?>
Output:
HAVING cli='paris' AND resp='James' AND type='emp'
HAVING type='emp'
use isset()..
e.g
$var1 = '';
if(isset($_GET['your_var']))
{
$var1 = $_GET['your_var']
//do your stuff here...
}
Related
// a simpler thing that would get me what I need is:
How do I concatenate each the values of a variable1 with each values of variable2
$Var1 = 'my1, my2, my3'; // here I have dozens of entries, they are symbols
$Var2 = 'word1, word2, word3'; // here also dozens of entries, are words.
How do I have all the keys of a variable, placed together of the keys of another variable?
$Values_that_I_needed = 'my1word1, my1word2, my1word3, my2word1, my2word2, my2word3, my3word1, my3word2, my3word3';
How would I build this values this variable up with all those values without having to type everything!?
Imagine an example with 60 my1, my2 … and 130 word1, word2 …. it’s my case!
Put each of the 60my before each of the 130 words !!
// I need to concatenate / join / join each values / keys of a variable, with all the values/keys of another variable, to avoid making all these combinations by hand. and put in another variable.
The solution using explode and trim functions:
$Var1 = 'my1, my2, my3'; // here I have dozens of entries, they are symbols
$Var2 = 'word1, word2, word3';
$result = "";
$var2_list = explode(',', $Var2);
foreach (explode(',', $Var1) as $w1) {
foreach ($var2_list as $w2) {
$result .= trim($w1) . trim($w2). ', ';
}
}
$result = trim($result, ', ');
print_r($result);
The output:
my1word1, my1word2, my1word3, my2word1, my2word2, my2word3, my3word1, my3word2, my3word3
Below cod should work if var1 and var2 have the same length
<?php
$tab1=explode(',',$var1);
$tab2=explode(',',$var2);
$c=$count($tab1);
$output='';
for($i=0;$i<$c;$i++){
$output.=$tab1[$i].$tab2[$i].', ';
}
echo $output;
$Var1 = 'my1, my2, my3';
$Var2 = 'word1, word2, word3';
$Array1 = explode(", ",$Var1); // create array from $Var1
$Array2 = explode(", ",$Var2); // create array from $Var2
foreach($Array1 as $My){
foreach($Array2 as $Word){
$Result[] = $My.$Word; // Join Var1 & Var2
}
}
$Values_that_I_needed = implode(", ", $Result);
echo $Values_that_I_needed; // my1word1, my1word2, my1word3, my2word1, my2word2, my2word3, my3word1, my3word2, my3word3
I want to convert my URLs into two parts e.g I have 4 urls like
c/category1
c/category2
p/page1
p/page2
Now what I extractly want is to convert URLs into two parts e.g.
$veriable_name1 = c
$veriable_name2 = category 1
or
$veriable_name1 = c
$veriable_name2 = category 2
or
$veriable_name1 = p
$veriable_name2 = page 1
or
$veriable_name1 = p
$veriable_name2 = page 2
In above examples C determines category and P determines Page. As i followed a tutorial to convert PHP urls into SEO friendly urls with PHP, but they only gave an example to convert urls by using PHP/MySQL from single table.
The code which i followed:
<?php
include('db.php');
if ($_GET['url']) {
$url = mysql_real_escape_string($_GET['url']);
$url = $url.'.html'; //Friendly URL
$sql = mysql_query("select title,body from blog where url='$url'");
$count = mysql_num_rows($sql);
$row = mysql_fetch_array($sql);
$title = $row['title'];
$body = $row['body'];
} else {
echo '404 Page.';
} ?>
HTML Part
<body>
<?php
if ($count) {
echo "<h1>$title</h1><div class='body'>$body</div>";
} else {
echo "<h1>404 Page.</h1>";
} ?>
</body>
but i have multiple links on my page and want to extract from multiple tables if other best suggestions
You need something like this:
$url = "c/category1";
$str_pos = strpos($url, "/");
$url_1 = substr($url, 0, $str_pos);
$url_2 = substr($url, $str_pos+1);
echo $url_1."<br/>";
echo $url_2;
Result:
c
category1
All your example "strings" are quite equal, so the easiest thing to do will be:
$url = 'c/category1';
$a = explode('/',$url);
$veriable_name1 = $a[0];
$veriable_name2 = $a[1];
or, to keep it a string function, you could run
$variable_name1 = strstr($url,'/',true);
$variable_name2 = str_replace('/','',strstr($url,'/'));
You can use explode for that:
$str = "c/category1";
list($variable_name1, $variable_name2) = explode('/', $str, 2);
var_dump($variable_name1);
var_dump($variable_name2);
//Output:
//string(1) "c" string(9) "category1"
U can use explode fn to do this. I have tried with strstr function.
Reference to strstr fn http://php.net/manual/en/function.strstr.php
$str = 'c/category';
$var2 = trim(strstr($str, '/'),'/');
echo $var2; // prints category
$var1 = strstr($str, '/', true); // As of PHP 5.3.0
echo $var1; // prints c
Note: it is applicable for [single slash oly] like c/category not for c/category/smg
You can also use a regular expression:
$url = "c/category1";
preg_match('/^(.+)\/(.+)$/', $url, $matches);
// check that the URL is well formatted:
if (count($matches) != 3) {die('problem');}
$veriable_name1 = $matches[1];
$veriable_name2 = $matches[2];
echo('"'.$veriable_name1.'" | "'.$veriable_name2.'"');
// it will show this: "c" | "category1"
Test the regex online [regex101.com].
i'm storing data in a database column like this.
1920,1927,3772,6127,3671
and i want to extract this value to variable as many as they are.
$var1 = 1920
$var2= 1927
$var3= 3772
$var4= 6127
$var5= 3671
and automatically read any new value WHILE there is "," comma and add it to a new var
Try something like this :
$vars = '1920,1927,3772,6127,3671';
$array_vars = explode(",",$vars);
foreach($array_vars as $key => $value){
${'var' . $key} = $value;
}
echo $var1;
Use explode function
$values = "1920,1927,3772,6127,3671";
$split_to_var = explode(',', $values);
$var1 = $split_to_var[0] ; // first one
echo $var1; // Returns 1920
It's not a very good idea to store them like this, but you can do it with explode.
$ar = explode(',',$initial_var);
Now you have the $ar array with all values and you can access them as $ar[1], $ar[2] etc.
You can use explode. something like below
$str = '1920,1927,3772,6127,3671';
$arr = explode(',' , $str);
//var_dump($arr);
For accessing the values use foreach
foreach($arr as $val){
//echo $val;
}
or
$var1 = $arr[0];
$var2 = $arr[1];
$var3 = $arr[2];
$var4 = $arr[3];
$var5 = $arr[4];
It is bad relational database technique to store information in this way. Break it into a separate table with a foreign key. This will make querying a lot easier and you won't have to worry about breaking up the string.
In the first time, I'm sorry for my disastrous english.
After three days trying to solve this, i give up.
Giving this array:
$names = array ( "James Walter Case", "Benjamin Wallace Pinkman", "Billy Elliot Newson" )
I have to extract the full name of the higher first stringlength word of each full name.
In this case, considering this condition Benjamin will be the higher name. Once
this name extracted, I have to print the full name.
Any ideas ? Thanks
How about this?
$names = array ( "James Walter Case", "Benjamin Wallace Pinkman", "Billy Elliot Newson" );
if (count($names) > 0)
{
$higher_score = 0;
foreach ($names as $name_key => $name_value)
{
$name_array = explode(" ", $name_value);
// echo("<br><b>name_array -></b><pre><font FACE='arial' size='-1'>"); print_r($name_array); echo("</font></pre><br>");
$first_name = $name_array[0];
// echo "first_name -> ".$first_name."<br>";
$score = strlen($first_name);
// echo "score -> ".$score."<br>";
if ($score > $higher_score)
{
$higher_score = $score;
$winner_key = $name_key; }
}
reset($names);
}
echo("longest first name is ".$names[$winner_key]." with ".$higher_score." letters.");
As said before, you can use array_map to get all the lenghts of the first strings, and then get the name based on the key of that value.
$names = array ( "James Walter Case", "Benjamin Wallace Pinkman", "Billy Elliot Newson" );
$x = array_map(
function ($a) {
$x = explode (" ", $a); // split the string
return strlen($x[0]); // get the first name
}
, $names);
$maxs = array_keys($x, max($x)); // get the max values (may have equals)
echo $names[$maxs[0]]; // get the first max
-- EDIT
Actually, there is a better way of doing this, considering this case. You can simply order the array by the lenght of the first names, and then get the first key:
usort($names,
function ($a, $b) {
$aa = explode(" ", $a); // split full name
$bb = explode(" ", $b); // split full name
if (strlen($aa[0]) > strlen($bb[0])){
return 0; // if a > b, return 0
} else {
return 1; // else return 1
}
}
);
echo $names[0]; // get top element
Allow me to provide a handmade solution.
<?php
$maxLength = 0;
$fullName = "";
$parts = array();
foreach($names as $name){
/* Exploding the name into parts.
* For instance, "James Walter Case" results in the following array :
* array("James", "Walter", "Case") */
$parts = explode(' ', $name);
if(strlen($parts[0]) > $maxLength){ // Compare first length to the maximum.
$maxLength = strlen($parts[0]);
$fullName = $name;
}
}
echo "Longest first name belongs to " . $fullName . " (" . $maxLength . " character(s))";
?>
Basically, we iterate over the array, split each name into parts (delimited by spaces), and try to find the maximum length among first parts of names ($parts[0]). This is basically a maximum search algorithm.
There may be better ways with PHP array_* functions, but well, this one gets pretty self-explanatory.
You can try something like..
$maxWordLength=0;
$maxWordIndex=null;
foreach ($names as $index=>$name){
$firstName=first(explode(' ',$name));
if (strlen($firstName)>maxWordLength){
$maxWordLength=strlen($firstName);
$maxWordIndex=$index;
}
}
if ($maxWordIndex){
echo $names[$maxWordIndex];
}
I have many links with parameter number - value is numbers between 1-1000
http://mysite.com?one=2&two=4&number=2
http://mysite.com?one=2&two=4&four=4&number=124
http://mysite.com?one=2&three=4&number=9
http://mysite.com?two=4&number=242
http://mysite.com?one=2&two=4&number=52
How can i remove from this parameter and value with PHP? I would like receive:
http://mysite.com?one=2&two=4
http://mysite.com?one=2&two=4&four=4
http://mysite.com?one=2&three=4
http://mysite.com?two=4
http://mysite.com?one=2&two=4
Try this:
$str = 'http://mysite.com?one=2&two=4&number=2';
$url = parse_url($str);
parse_str($url['query'], $now );
unset($now['number']);
foreach($now as $key=>$value) :
if(is_bool($value) ){
$now[$key] = ($value) ? 'true' : 'false';
}
endforeach;
$options_string=http_build_query($now);
echo $url = 'http://mysite.com?'.$options_string;
Reference : PHP function to build query string from array - not http build query
Like this
$urls = '
http://mysite.com?one=2&two=4&number=2
http://mysite.com?one=2&two=4&four=4&number=124
http://mysite.com?one=2&three=4&number=9
http://mysite.com?two=4&number=242
http://mysite.com?one=2&two=4&number=52
';
echo '<pre>';
echo preg_replace('#&number=\d+#', '', $urls);
you can build a redirection after building a new URL with $_GET['one']
Use bellow steps,this is clear aproach
1- Parse the url into an array with parse_url()
2- Extract the query portion, decompose that into an array
3- Delete the query parameters you want by unset() them from the array
4- Rebuild the original url using http_build_query()
hope this help you
You could use parse_str() which parses the string into variables. In that way you can separate them easily
I wrote example of code.
<?php
$arr = array();
$arr[] = 'http://mysite.com?one=2&two=4&number=2';
$arr[] = 'http://mysite.com?one=2&two=4&four=4&number=124';
$arr[] = 'http://mysite.com?one=2&three=4&number=9';
$arr[] = 'http://mysite.com?two=4&number=242';
$arr[] = 'http://mysite.com?one=2&two=4&number=52';
function remove_invalid_arguments(array $array_invalid, $urlString)
{
$info = array();
parse_str($urlString, $info);
foreach($array_invalid as $inv)
if(array_key_exists($inv,$info)) unset($info[$inv]);
$ret = "";
$i = 0;
foreach($info as $k=>$v)
$ret .= ($i++ ? "&" : ""). "$k=$v"; //maybe urlencode also :)
return $ret;
}
//usage
$invalid = array('number'); //array of forbidden params
foreach($arr as $k=>&$v) $v =remove_invalid_arguments($invalid, $arr[1]);
print_r($arr);
?>
Working DEMO
If "&number=" is ALWAYS after the important parameters, I'd use str_split (or explode).
The more sure way is to use parse_url(),parse_str() and http_build_query() to break the URLs down and put them back together.
As per example of your url -
$s='http://mysite.com?one=2&two=4&number=2&number2=200';
$temp =explode('&',$s);
array_pop($temp);
echo $newurl = implode("&", $last);
Output is :http://mysite.com?one=2&two=4&number=2
Have a look at this one using regex: (as an alternative, preferably use a parser)
(.+?)(?:&number=\d+)
Assuming &number=2 is the last parameter. This regex will keep the whole url except the last parameter number