Welcome Guest, Not a member yet? Register   Sign In
Having trouble with a foreach loop
#1

Hi there,

I am trying to figure out why I am getting either undefined index error or non-object error.

PHP Code:
private function checkForBot(){
 
      
       $keywords 
$this->Content_model->get_results('analytics_bots');
 
      $agent strtolower($_SERVER['HTTP_USER_AGENT']);
 
      foreach ($keywords->keyword as $key) {
 
          if(strpos($agent$key) !== false){
 
          return true;
 
                
       
}
 
      return false;
 
   

if I use $keywords->keyword I am getting the non-object and if I use $keywords['keyword']I get the index error.

I just cannot figure out why its not accepting the array in.

Thanks,

Doomie
Reply
#2

PHP Code:
foreach ($arr as $value)
{
 
   // Object
}

foreach (
$arr as $key => $value)
{
 
   // Associated Array

What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3

Just use var_dump($keywords) to find out what exactly the content is (and type of data) of that variable.

You say it suppose to be an array, so have you tried:
PHP Code:
foreach ($keywords as $key => $keyword) {
 
  ...


That being said, you do know that CodeIgniter has some useragent detection build in?

PHP Code:
$this->load->library('user_agent');

if (
$this->agent->is_robot()) {
 
   ...


https://www.codeigniter.com/userguide3/l...agent.html
Reply
#4

(09-15-2016, 06:25 AM)Diederik Wrote: Just use var_dump($keywords) to find out what exactly the content is (and type of data) of that variable.

You say it suppose to be an array, so have you tried:
PHP Code:
foreach ($keywords as $key => $keyword) {
 
  ...


That being said, you do know that CodeIgniter has some useragent detection build in?

PHP Code:
$this->load->library('user_agent');

if (
$this->agent->is_robot()) {
 
   ...


https://www.codeigniter.com/userguide3/l...agent.html

Thank you so much for this.

One small question about it, I am trying to figure out the parse section in user_agent.  I am seeing that sites are able to get resolutions and device names (if they are mobile) can you use parse to get this sort of info and if so, how?

Thanks,
Doomie
Reply
#5

The Codeigniter useragent library is pretty basic. You could integrate https://github.com/serbanghita/Mobile-Detect into your project. It provides functions like is_mobile, is_tablet etc.
If you want to know screen resolutions you need to adopt some javascript solutions. I use this approach: https://github.com/hgoebl/mobile-detect..../README.md

Pretty easy to combine it with modernizr to append the desired classnames to the body tag.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB