Im trying to begin to work with a API to call a few bits of information
The documentation for it is quite scarse and the support is quite slim however it is quite good in its way
Ive recently started to learn bits about arrays etc however im not too sure if that would be my hurdle on this specific question
the one part of the API im struggling on is this:
// Get the character object. Will return FALSE if the
// character could not be found or character is frozen.
$character = $armory->getCharacter('xxxx');
Now im quite stuck on how to find if its "FALSE"
This is an extract from the class file if its any help for you guys:
function __construct($region, $realm, $character, $ignoreFields = FALSE) {
if ($ignoreFields != FALSE){
$this->excludeFields($ignoreFields);
}
$this->region = strtolower($region);
$this->realm = $realm;
$this->name = $character;
$jsonConnect = new jsonConnect();
$this->characterData = $jsonConnect->getCharacter($character, $realm, $region, implode(",",$this->fields));
if ($this->characterData != FALSE){
$this->name = $this->characterData['name'];
$this->setTitles();
$this->setTalentTreeSelected();
$this->race = new Races($region);
$this->class = new Classes($region);
} else {
return FALSE;
}
return TRUE;
}
https://sourceforge.net/p/wowarmoryapi/home/ is the API if any of you wish to see the full api or command list
thanks
if ($character->isValid() === false) {
//your code that runs if there is no character
}
else {
//your code that runs if everything is fine
}
if ($character) {
// true stuff
} else {
// false stuff
}
Many things evaluate to logical "false" in php:
Numeric value 0,
Empty string,
Undefined/uninitialized variable
Empty array etc. etc.
Related
I'm trying to check for if a string contains any blacklisted words from an array of string.
This is my current code - the focus is efficiency, string from list may be empty, the string we search in is never empty:
public static function includes_from_array($stringArray, $searchInMe, $offset=0) : bool {
// if not array just check if $stringArray exists in our $searchInMe string.
if(!is_array($stringArray)) {
return strpos($stringArray, $searchInMe) !== false;
}
foreach($stringArray as $query) {
if ($query === '') {
continue;
}
else if(strpos($searchInMe, strtolower($query), $offset) !== false) {
return true;
}
}
return false;
}
Is there a way to shorten the code quickly without harming efficiency or even improving it?
The code was written as it is currently to be able to retrieve the position if required (changing from true or false to pos returned in check), however it is not required in the shortened version.
Thanks!
As per my understanding you soul purpose is to check any bad word is present in sentence or URL and if present then return Boolean true.
Kindly try like this:
<?php
function includes_from_array($stringArray, $searchInMe){
if(is_array($stringArray)){
foreach($stringArray as $arr){
if(strpos($searchInMe,$arr) !== false){
return true;
}
}
}else{
if(strpos($searchInMe,$stringArray) !== false){
return true;
}
}
return false;
}
Sample Output : https://3v4l.org/3Pefn
I am looking to find a way to detect cycle in linked list using Array in PHP. Please note I am aware of two pointer approach but I am keen on understanding approach if it is feasible to achieve this with php array.
in Java code sample on leetcode is as below:
public boolean hasCycle(ListNode head) {
Set<ListNode> nodesSeen = new HashSet<>();
while (head != null) {
if (nodesSeen.contains(head)) {
return true;
} else {
nodesSeen.add(head);
}
head = head.next;
}
return false;
}
Based on the given info I would rewrite it like this utilizing also an array as hashmap for visited nodes.
function hasCycle(SplDoublyLinkedList $list): bool
{
$nodesSeen = [];
$list->rewind();
while ($current = $list->current()) {
if (isset($nodesSeen[$current]))
return true;
$nodesSeen[$current] = true;
$list->next();
}
return false;
}
Testing with having a cycle on a.
$list = new SplDoublyLinkedList();
$list->push('a');
$list->push('b');
$list->push('c');
$list->push('a');
var_dump(hasCycle($list));
true
Testing with having no cycle.
$list = new SplDoublyLinkedList();
$list->push('a');
$list->push('b');
$list->push('c');
$list->push('d');
var_dump(hasCycle($list));
false
one more approach I have come across (no that efficient though):
function hasCycle($head) {
$prev = [];
while($head){
if(in_array($head, $prev)) {
return true;
}
$prev[] = $head;
$head= $head->next;
}
return false;
}
im just learning php
Im trying to add a log with comments to my functions output.
Right now it looks like this:
//the function
function add1($x){
if($GLOBALS['logging'] === 'on'){ $log[] = 'Adding 1 to '.$x;};
$a = $x + 1;
if($GLOBALS['logging'] === 'on'){
$return[] = $a;
$return[] = $log;
return $return;
}else{ return $a; };
};
//calling the function
if($GLOBALS['logging'] === 'on'){
$return = add1($x);
$number = $return[0];
$log = $return[1];
}else{ $number = add1($x); };
Im kinda annoyed by the fact i need to retype this if statement.
So i made a seperate function for returning the function
which looks like this:
//function
function log_return($data = 'x', $log = 'x'){
if($GLOBALS['logging'] === 'on'){
if($data !== 'x') $return[] = $data;
if($log !== 'x') $return[] = $log;
return $return;
} return $data;
};//function end
And returning it with:
return $return = isset($log) ? log_return($data, $log) : log_return($data);
Now my quastion is: Is there a way to call a function with function..
like:
call_function(add1($x));
so i can return it either with log or without..
Given the answer https://stackoverflow.com/a/2700760/5387193 - this should work:
function add1($a)
{
// add1 code goes here
}
function call_function($name, $param)
{
$name($param);
}
call_function('add1', $x);
On a side note, your variable and function names aren't very intuitive. Perhaps you should study how to write good quality readable code. I recommend reading chapter 9 of Refactoring by Martin Fowler, it's quite good. You can find a PDF version on the web.
Another note, your return statement return $return = isset($log) ? log_return($data, $log) : log_return($data); has a unnecessary assignment to $return. The code should simply read
return isset($log) ? log_return($data, $log) : log_return($data);
Yes, it is possible. To simplify:
function first($x) {
return $x+1;
}
function second($y) {
return $y+1;
}
echo second(first(1)); // Returns 3, ie. 1+1+1
As gview said in his comment, don't use global variables. Argument lists exist for several reasons, included but not limited to making code easier to read, edit, and debug. The same goes for function and variable names.
Moreover, your code is very messy. It can be consolidated:
function addTo($currentValue, $valueToAdd, $logging = 0)
{
if ($logging) {
logWrite('addTo', "Adding $valueToAdd to $currentValue");
return $currentValue + $valueToAdd;
} else {
return $currentValue;
}
}
function logWrite($operation, $message)
{
$log = getLog(); // maybe it's a file, or DB record or something
// perform the write, depending on your implementation
}
$number = addTo($someStaringValue, $someOtherValue, 1);
All of this said, logging should not control program flow. In other words, whether something is logged by the system or not should have no bearing on what your code is trying to do. I really think you need to take a broader view of what you're trying to do and break it up into components.
At best, your code should tell a logger to log info, and the logger itself should determine if logging is actually turned on. If it is, the info is logged. If not, then the code that calls on the logger still works and goes about its business.
I'm stuck in Drupal Panels / PHP Access plugins.
At least, now I found the three conditions to create my final snippet. the purpose of it is to return TRUE; if "condition1 is TRUE" OR "condition2 is TRUE" OR "condition3 is TRUE". I found a lot of similar questions, but the last condition force me to post here to find the right way to do this.
Condition 1:
// At least $view1->result has result.
$view1 = views_get_view('sp_onglet_videos');
$view1->set_display('views-tab-embed_1');
$output1 = $view1->preview();
if ($view1->result) {
return TRUE;
}
Condition 2 (same thing):
// At least $view2->result has result.
$view2 = views_get_view('sp_onglet_audio');
$view2->set_display('views-tab-default');
$output2 = $view2->preview();
if ($view2->result) {
return TRUE;
}
Condition 3 is more complex:
// Checks for content in the field field_txt_videos.
if (isset($contexts['argument_nid_1']->data-> field_txt_videos)) {
$field = $contexts['argument_nid_1']->data-> field_txt_videos;
if (is_null($field)) {
return FALSE;
}
if (is_array($field)) {
foreach ($field as $key => $val) {
if (is_array($val)) {
$field[$key] = array_filter($val);
}
}
$field = array_filter($field);
return count($field);
}
if (is_string($field) && trim($field) == '') {
return FALSE;
}
if ($field) {
return TRUE;
}
return FALSE;
}
I would like to have something clean (and functional) like this:
if ($view1->result && $view2->result && $field) {
return TRUE;
}
But it's to tricky for my php knowledge. Need a little help !
You want to save the result of the 3rd condition (into a variable) and use this result to run your final condition/query. But you can query the 3rd condition if it is a function.
It is better to properly space your code and use plenty of newlines.
However, PHP does have some pretty cool tricks to do assignment inside conditional statements.
if(($view1 = views_get_view('sp_onglet_videos')) AND $view1->set_display('views-tab-embed_1') AND ($output1 = $view1->preview()) AND $view1->result) return TRUE;
However, as you can see this code is a mess - don't do it unless your assignment is really small. Take this simple security check at the top of a PHP file:
<?php defined('BASE_PATH') OR die('Not Allowed');
After two hours of head scratching and googling - i'm stuck!
As per the title I'm trying to return an array that is built up as the function loops through. I want to only return the array variable on the else however it will not co-operate. It simply returns as blank away from the function, however within the else I can print_r it and shows as expected. It just simply won't return the array in the $open_array variable. Any ideas (or abuse) would be greatfully appreciated!
function find_parent($number, $open = false) {
if(isset($other_variable[$number])) {
foreach($other_variable[$number] as $val) {
$open[$val->id] = [$val->id;
$open = find_parent([$val->id, $open);
}
}
else {
return $open;
}
}
$open_array = find_parent($number);
print_r($open_array);
In the "then" part, you assign to $open, but then never return that value. So you can't really expect to ever get something back, except in those cases where you enter the else part, but then it's an unchanged version.
So here's what I'd do: I'd go with a version without returning $open ever.
Initialize $open before you call the function.
Pass it on.
Then modify it where necessary.
There's no reason really to return this $open value since you're passing it on by reference anyway, i.e. it should always be the same object which you're manipulating (and in those cases that it isn't, it's probably a bug).
This way, you can concentrate on the flow logic with your calls and returns, and be sure you always talk to the same datastructure.
update
function find_parent($number, $open = false) {
if(isset($other_variable[$number])) {
foreach($other_variable[$number] as $val) {
$open[$val->id] = [$val->id;
$open = find_parent([$val->id, $open);
return $open; // INSERTED
}
}
else {
return $open;
}
}