I'm trying to check if the following is empty or not.
{"players":""}
I have a function that gets that from an api/site and.. well, heres the code.
function getPlayers($server) {
// Fetches content from url and json_decodes it
$playersList = getUrl('http://api.iamphoenix.me/list/?server_ip=' . $server);
// Attempting to check if it's empty.
if ($playersList != "") {
// convert list of comma-separated names into array
$players = explode(',', $playersList->players);
foreach ($players as $player) {
echo '<img title="'.$player.'" src="https://minotar.net/avatar/'.$player.'/32">';
}
} else {
return 'empty';
}
}
However, using !=, empty(), or isset(), I still get an empty string, example:
https://minotar.net/avatar//32
Where it should be..
https://minotar.net/avatar/Notch/32
When it's empty, I'd like it to just return 'empty'.
I'm not sure what I'm doing wrong. Any ideas?
In pure php you can check the url segments like
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', $_SERVER['REQUEST_URI_PATH']);
if($segments[2] == '') {
}
//or
if(empty($segments[2])) {
}
//or do your condition
if you are using codeigniter you might say
if(empty($this->uri->segment(2)))
But be sure you loaded the url helper
Hope I understand your question!
Since you were able to have some output, see my changes in the codes.
function getPlayers($server) {
// Fetches content from url and json_decodes it
$playersList = getUrl('http://api.iamphoenix.me/list/?server_ip=' . $server);
// Attempting to check if it's empty.
if ($playersList != "") {
// convert list of comma-separated names into array
$players = explode(',', $playersList->players);
// check conversion
if(is_array($players) && !empty($players){
foreach ($players as $player) {
echo '<img title="'.$player.'" src="https://minotar.net/avatar/'.$player.'/32">';
}
} else {
return 'empty';
}
} else {
return 'empty';
}
}
You should do this;
print_r($playersList);
just after you set it to see what it actually is. My guess is that you are not getting what you suspect from the getURL call.
Add one more equals sign to take type comparison into account as well
if ($playerList !== '')
try this
if (isset($playersList) && is_array($playersList) && !empty($playersList)) {
// convert list of comma-separated names into array
$players = explode(',', $playersList->players);
foreach ($players as $player) {
echo '<img title="'.$player.'" src="https://minotar.net/avatar/'.$player.'/32">';
}
} else {
return 'empty';
}
Related
I need one help. I need to check that string is present inside array or not and also it should search letter wise using PHP. I am explaining my code below.
$resultArr=array("9937229853","9937229856","9937229875");
$searchValue="+919937229853";
Here I need to check that some of the value from $searchValue is present inside in array or not. I am doing like below but its not giving me the proper result.
$searchValue="+919937229853";
$resultArr=array("9937229853","9937229856","9937229875");
if(!in_array($searchValue, $resultArr))
{
$flag=1;
}else{
$flag=0;
}
echo $flag;
As per my requirement here result should print 1 because some value from $searchValue also present in that array but the echo result is coming 0.Please help me.
$searchValue="+919937229853";
$resultArr=array("9937229853","9937229856","9937229875");
foreach($resultArr as $value)
{
if(strpos($value,$searchValue) || strpos($searchValue,$value) || $searchValue==$value)
{
$flag = 1;
break;
}
else
$flag=0;
}
echo $flag;
I think this will do what you are looking for. in_array() method search string in array but for the exact string. strpos can search substring in long string and return the offset number or the index of substring in the long string.
you can try code like below.
if(!in_array(substr($searchValue,-10), $resultArr))
$searchValue="+919937229853";
$searchValue = str_replace("+91","",$searchValue);
$resultArr=array("9937229853","9937229856","9937229875");
if(in_array($searchValue, $resultArr))
{
$flag=1;
}else{
$flag=0;
}
echo $flag;
User str_replace function replace first three charater from string
$flag=0;
for($i=0;$i<strcmp($searchValue);$i++){
for($j=0;$j<strcmp($searchValue);$j++){
$part=substr($searchValue,$i,$j)
array_filter($resultArr, function($el) use ($part) {
if ( strpos($el, $part) !== false ){
$flag=1;
}
});
}
}
The function below will return true if either
your $searchValue is in the array (in_array), or
if any item of the array is a substring of $searchValue
in other words: If part of $searchValue is in the array.
This is the code and how you call it:
function search($needle, $haystack) {
// is $needle contained in the array as it is?
if (in_array($needle, $haystack))
return true;
// Is any part of $needle part of the array?
foreach ($haystack as $value) {
if (strpos($needle, $value) !== FALSE)
return true;
}
return false;
}
$resultArr = array("9937229853", "9937229856", "9937229875");
$searchValue = "+919937229853";
$result = search($searchValue, $resultArr);
var_dump($result);
The parameter is taken from the url like this file.php?item=xyz
I have an array $_SESSION['arr'].
Now I want to check if xyz is present in $_SESSION['arr'] and delete it if it is present.
In the end I send my result to the calling JQuery function as
echo json_encode($_SESSION['arr']);
EDIT: And if the element is not present, add it to the array.
Thanks in advance!
This should work for you :)
foreach ($_SESSION['arr'] as $value)
{
//converting to lowercase
$value= strtolower($value)
if($value == "xyz")
{
//removing $value from $_SESSION['arr']
unset($_SESSION['arr'][$value]);
}
else
{
//adding value to array
array_push($_SESSION['arr'], "xzy");
}
}
Use below code.
if(isset($_GET['item']) && $_GET['item'] == "xyz")
{
if(in_array($_GET['item'],$_SESSION['arr']))
{
//Delete it
}
}
if(isset($_GET['item']))
{
if(in_array($_GET['item'],$_SESSION['arr']))
{
$pos = array_search($_GET['item'], $_SESSION['arr']);
unset($_SESSION['arr'][$pos]);// deletes
}
not tested but logic like this. hope helps :)
In my page, there are multiple $_GET values. ie
if(isset($_GET["projects"]))
{ ..... }
else if(isset($_GET["research"]))
{ ...... }
else if(isset($_GET["publication"]))
{ ..... }
...upto 10 elseif's
Can I shorten this?
Can I get these values {projects,research, publication,..} in a variable.?
Ok so I guess I figured out what you want from your comments. Lets see.
$types = array('projects', 'research', 'publication'); // add as many as you want
$valid = array_intersect_key($_GET, array_flip($types));
if (count($valid) > 1)
die "More than one category is set, this is invalid.";
if (!$valid)
die "No category was set, you must choose one.";
foreach ($valid as $type => $value) // just to split this one element array key/value into distinct variables
{
$value = mysql_real_escape_string($value); // assuming you are using mysql_*
$sql = "SELECT * FROM table WHERE $type = '$value'";
}
...
Yes, you can assign these in a variable -
if(isset($_GET["projects"]))
{
$value = $_GET['projects'];
}
else if(isset($_GET["research"]))
{
$value = $_GET['research'];
}
else if(isset($_GET["publication"]))
{
$value = $_GET['publication'];
}
echo $value;
I'm guessing you're expecting a single value in $_GET, like ?projects=foo or ?research=bar. In that case:
$type = key($_GET);
$value = $_GET[$type];
echo "$type = $value";
$projects = $_GET["projects"];
Or just use directly from $_GET, this is an associative array with all the values.
foreach ($_GET as $key => $value){
if(!empty($value)){
$type = $key; //if you expect a single item
$type[] = $key; //if you expect multiple items
}
}
if the intent is to check if values on a form have been answered/filled out you could use
if(isset($_GET['project'] || ... || isset($_GET['publication'])
{
// Insert Code Here
}
else
{
// Insert Code Here
}
The above code is assuming the fields are not text fields or textareas if those are the types of inputs then instead of
if(isset($_GET['project']))
use
if($_GET['project'] != "")
I didn't completely understood what you are saying but looks like that you are trying to execute something when all $_GET is true. If so then use the code below
if(isset($_GET["projects"]) && isset($_GET["research"]) && isset($_GET["publication"]) )
{ ..... }
Hope this helps you
I have a simple data format that goes as follows:
stuff/stuff/stuff
An example would be:
data/test/hello/hello2
In order to retrieve a certain piece of data, one would use my parser, which tries to do the following:
In data/test/hello/hello2
You want to retrieve the data under data/test (which is hello). My parser's code is below:
function getData($data, $pattern)
{
$info = false;
$dataLineArray = explode("\n", $data);
foreach($dataLineArray as &$line)
{
if (strpos($line,$pattern) !== false) {
$lineArray = explode("/", $line);
$patternArray = explode("/", $pattern);
$iteration = 0;
foreach($lineArray as &$lineData)
{
if($patternArray[$iteration] == $lineData)
{
$iteration++;
}
else
{
$info = $lineData;
}
}
}
}
return $info;
}
However, it always seems to return the last item, which in this case is hello2:
echo getData("data/test/hello/hello2", "data/test");
Gives Me;
hello2
What am I doing wrong?
If you want the first element after the pattern, put break in the loop:
foreach($lineArray as $lineData)
{
if($patternArray[$iteration] == $lineData)
{
$iteration++;
}
elseif ($iteration == count($patternArray))
{
$info = $lineData;
break;
}
}
I also check $iteration == count($patternArray) so that it won't return intermediate elements, e.g.
/data/foo/test/hello/hello2
will return hello rather than foo.
P.S. There doesn't seem to be any reason to use references instead of ordinary variables in your loops, since you never assign to the reference variables.
Consider the following:
<input type="hidden" name="random[variable][here]" value="valueofrandom"/>
Is there a better way to retrieve its value if we have the name as a string? The following works, but it doesn't seem very smart.
function getPostValueFromName($name) {
// Example string name: random[variable][here]
$parts = preg_split('/\[|\]/i', $name, -1, PREG_SPLIT_NO_EMPTY);
if (isset($parts[3])) {
return $_POST[$parts[0]][$parts[1]][$parts[2][$parts[3]]];
} elseif (isset($parts[2])) {
return $_POST[$parts[0]][$parts[1]][$parts[2]];
} elseif (isset($parts[1])) {
return $_POST[$parts[0]][$parts[1]];
} else {
return $_POST[$parts[0]];
}
}
Thanks!
I use https://github.com/symfony/PropertyAccess for things like this.
Using it, you can get random[variable][here] with
$accessor = new PropertyAccessor();
$val = $accessor->getValue($_POST, 'random.variable.here');
// or
$val = $accessor->getValue($_POST, 'random[variable][here]');