my sample code is here
include 'simple_html_dom.php';
function get_all_links($url){
global $host;
$html = new simple_html_dom();
$html->load(file_get_contents($url));
foreach($html->find('a') as $a){
$host1 = parse_url($a->href);
$host = parse_url($url);
if($host1['host'] == $host['host']){
$data[] = $a->href;
}
}
return $data;
}
$links = get_all_links("http://www.example.com/");
foreach($links as $link){
echo $link."<br />";
}
When I try this code, I got this error: Notice: Undefined index: host in... What's wrong in my code? Please suggest me some helping code, Thanks in Advance.
You need to check if the arrays contain entries for 'host' using isset before assuming they exist:
if (isset($host1['host']) && isset($host['host'])
&& $host1['host'] == $host['host']) {
Or you can use # to suppress warnings from the check.
if (#$host1['host'] == #$host['host']) {
However, you'll need to double-check that the latter works as you desire when both are missing.
Update: As the others pointed out there is also array_key_exists. It will handle null array values whereas isset returns false for null values.
As others have answered, both isset() and array_key_exists() will work here. isset() is nice, because it can actually take multiple arguments:
if (isset($array[0], $array[1], $array[2]))
{
// ...
}
// same as
if (isset($array[0]) && isset($array[1]) && isset($array[2]))
{
// ...
}
Returning true only if all arguments are set.
you can find out if an array has an index called "host" using array_key_exists
if (array_key_exists($host, "host") && array_key_exists($host1, "host") && ...)
http://us3.php.net/manual/en/function.array-key-exists.php
Related
I have the following code:
if ($login->messages || $content->messages) {
echo '<div id="message">';
foreach ($login->messages as $message) {
echo $message;
} foreach ($content->messages as $message) {
echo $message;
}
echo '</div>';
}
Where both $login->messages and $content->messages are arrays that may be empty. When $login->messages is empty but $content->messages is not, things work fine and the messages in $content->messages are displayed However, when $login->messages has something and $content->messages is empty, the login messages are shown, then I get the error "Warning: Invalid argument supplied for foreach() in" under the messages. I don't see what I'm doing wrong.
Thank you.
Either $login->messages or $content->messages is not an array. You may think they are an empty array - but they are probably actually false, null, '', or 0.
I would check them with var_dump() to see their type.
if ($login->messages || $content->messages)
why don't you check if count() > 0
You are checking with a conditional OR and then go on to use both variables.
if ($login->messages || $content->messages)
The statement will return true if either $messages contain data.
You should check that both values are not empty with an AND.
if ($login->messages && $content->messages)
Even better would be a type check:
if (is_array($login->messages) && is_array($login->messages))
There are several ways to check a array is empty or not.
You also apply this way that means if you cast any value to an array, you get an array whatever value it was. For instance null,true,false all result in an empty array.
if ($login->messages || $content->messages) {
echo '<div id="message">';
foreach ((array)$login->messages as $message) {
echo $message;
} foreach ((array)$content->messages as $message) {
echo $message;
}
echo '</div>';
}
In JavaScript, I can do this:
var somevar = {
propertyTwo : false,
propertyThree : "hello!"
}
var test = somevar.propertyOne || somevar.propertyTwo || somevar.propertyThree
alert(test); //displays "hello!"
Is there a similar functionality in PHP for this?
Haven't been able to find anything online.
I tried this, but PHP just treats it like a comparison and echo's 1 (true)
$somevar = array(
'propertyTwo' => false,
'propertyThree' => "hello!"
);
$test = $somevar['propertyOne'] || $somevar['propertyTwo'] || $somevar['propertyThree'];
echo $test; //displays '1'
Not really a big deal if there isn't, but I figured that with all of the bells and whistles provided in php 5.x, there would be some kind of shorthand for assigning the first true value in a list of values to a single variable like that.
I suppose I could write a function.
EDIT :
As I suspected, PHP doesn't have the same quirk.
Quick function I wrote
function assign_list($list){
foreach($list as $v)
if(isset($v) && $v) return $v;
return false;
}
Just pass it an array of stuff
The following will work in PHP >= 5.3, but you will still receive a Notice Error because propertyOne is not defined.
<?php
$somevar = array(
'propertyTwo' => false,
'propertyThree' => "hello!"
);
$test = $somevar['propertyOne'] ?: $somevar['propertyTwo'] ?: $somevar['propertyThree'];
echo $test; //displays 'hello!'
You could however work around this by supressing the variables, but it is highly unrecommended:
$test = #$somevar['propertyOne'] ?: #$somevar['propertyTwo'] ?: #$somevar['propertyThree'];
This doesn't work in PHP, and here's why:
$somevar['propertyOne'] = false;
$somevar['propertyTwo'] = true;
$test = $somevar['propertyOne'] || $somevar['propertyTwo'];
Imagine typing that query into an if statement:
if( $somevar['propertyOne'] || $somevar['propertyTwo'] ){ ... }
This will return true (evaluates to 1) if either variable is true.
Now, if we make all of the variables = false:
$somevar['propertyOne'] = false;
$somevar['propertyTwo'] = false;
$test = $somevar['propertyOne'] || $somevar['propertyTwo'];
The variable returns false (evaluates to 0).
Another thing we can do is:
$somevar['propertyOne'] = true;
$somevar['propertyTwo'] = true;
$test = $somevar['propertyOne'] && $somevar['propertyTwo'];
This will return true (evaluates to 1) as both variables meet the criteria.
This means that we can do things like this in PHP though:
$test = $somevar['propertyOne'] || $somevar['propertyTwo'];
if($test){ ... }
TL,DR: In PHP you are storing the result of the expression into a variable, not doing any validation on anything.
I'm receiving the fooling error below but not sure why. the $_Post all have data.
error: Warning: Invalid argument supplied for foreach() in /home/soc/process_member.php on line 19
$valid = true;
foreach($_POST['add'] && $_POST['cpl'] as $value) {
if(!isset($value)) {
$valid = false;
}
}
if(!$valid) {
$err .= 'please fill in all fields';
$en['reg_error'] = '<div class=err style="color: #FF0000;"><b>'._error.': '.$err.'</b></div><br>';
load_template('modules/members/templates/s_reg.tpl');
}
You should read more about PHP. There are two syntaxes for "foreach":
foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement
This is totally wrong:
foreach($_POST['add'] && $_POST['cpl'] as $value) {
Let me give you an example:
<?php
foreach (array(1, 2, 3, 4) as &$value) {
$value = $value * 2;
}
?>
For more info, check the official PHP Documentation regarding foreach: http://php.net/manual/en/control-structures.foreach.php
I think what you want is a merged array:
foreach(array_merge($_POST['add'], $_POST['cpl']) as $value) {
// ...
First, in PHP, result of && operation is always boolean (i.e., true or false) - and you cannot supply it into foreach (and why you may wish to?), hence the error.
Second, even if it were possible, it'd still make little sense to use isset here: if either $_POST['add'] or $_POST['cpl'] is indeed unset, the notice is raised.
So, you can either just rewrite the first section of your code like this:
$valid = isset($_POST['add']) && isset($_POST['cpl']);
... or, taking into account the flexible nature of isset construct, just...
$valid = isset($_POST['add'], $_POST['cpl']);
... because, as said in its' official doc:
If multiple parameters are supplied then isset() will return TRUE only
if all of the parameters are set. Evaluation goes from left to right
and stops as soon as an unset variable is encountered.
If there's actually a whole big set of args to check and/or you're too lazy to type '$_POST' each time, use foreach to go through the array of their names (and not the actual values!) instead:
$valid = true;
foreach (array('add', 'cpl', 'whatever', 'it', 'takes') as $argName) {
if (! isset($_POST[$argName])) {
$valid = false;
break;
}
}
I have looked but it seems I can't find the right answer or I don't have the skills for that. The thing is I'm getting this error:
Notice: Undefined variable: node in include() (line 69 of /home/xwebmedia/public_html/ltr/sites/all/themes/ltr/page.tpl.php).
and the code I'm using is:
<?php
if (count($node->field_adds) != 0)
{
foreach($node->field_adds['und'] as $key => $value)
{
$nid = $value['nid'];
$mywidget = node_view(node_load($nid));
print drupal_render($mywidget);
}
}
?>
Thing is everything is working fine, I get my widgets with adds in sidebar, but I am having this notice of error.
I know that I need to define a variable in template.php but I tried something it didn't work.
Any suggestions?
Check that $node has been set.
<?php
if (isset($node) && count($node->field_adds) != 0)
{
foreach($node->field_adds['und'] as $key => $value)
{
$nid = $value['nid'];
$mywidget = node_view(node_load($nid));
print drupal_render($mywidget);
}
}
?>
The page template file doesn't have a $node variable by default (you can have pages that aren't nodes so it's not required).
The menu_get_object() function is your friend here:
$node = menu_get_object();
if ($node) {
...
}
One of my colleges seem to have an 'undefined index' error on a code I wrote
This code of mine looks like this:
if ( is_array ($arr['key']))
My intention was to check whether $arr has a key named 'key', and if the value of that key is array itself. Should I do instead: if( isset($arr['key']) && is_array ($arr['key'])) ?
Maybe the following is equivavlent:
Let's assume $var is not set. Then, will is_array($var) cause an error or will it just return false?
Thank you
Yes, use isset, then is_array.
if(isset($arr['key']) && is_array($arr['key'])) {
// ...
}
Because PHP uses short-circuit logic evaluation, it will stop before it gets to is_array(), so you'll never get an error.
Try:
is_array($arr) && array_key_exists('key', $arr)
check if it exists first, then if its an array. Otherwise you will still get the same error.
if ( isset($arr['key'])) {
if (is_array ($arr['key']) {
}
}
Maybe you can consider a generic get() function for safe-retrieving data from arrays:
/*
Get with safety
#author: boctulus
#param array
#param index1
#param index2
..
*/
function get(){
$numargs = func_num_args();
$arg_list = func_get_args();
$v = $arg_list[0];
for ($i = 1; $i < $numargs; $i++)
{
if (isset($v[$arg_list[$i]]))
$v = $v[$arg_list[$i]];
else
return null;
}
return $v;
}
Use:
$arr = [];
var_dump( get($arr,'a','b') ); // NULL
$arr['a']['b'] = 'ab';
var_dump( get($arr,'a','b') ); // 'ab'