728x90


I am running a PHP script, and keep getting errors like:

Notice: Undefined variable: my_variable_name in C:\wamp\www\mypath\index.php on line 10

Notice: Undefined index: my_index C:\wamp\www\mypath\index.php on line 11

Line 10 and 11 looks like this:

echo "My variable value is: " . $my_variable_name;
echo "My index value is: " . $my_array["my_index"];

What do these errors mean?

Why do they appear all of a sudden? I used to use this script for years and I've never had any problem.

What do I need to do to fix them?

This is a General Reference question for people to link to as duplicate, instead of having to explain the issue over and over again. I feel this is necessary because most real-world answers on this issue are very specific.

Related Meta discussion:

shareimprove this question
6 
2 
the variable might not have been initialized. Are you initializing the variable from a post or get or any array? If that's the case you might not have an field in that array. That your accessing. – ASK Dec 15 '15 at 13:12
1 
@ChrisJJ, Robbie's answer explains this very well. – Leith Nov 24 '16 at 7:29
3 
@Pekka웃 - I noticed the edit adding the "and "Notice: Undefined offset"" - Wouldn't it make more sense using "PHP: “Undefined variable”, “Undefined index”, “Undefined offset” notices" (even take out the PHP, since it is tagged as "php". Plus, the URL gets cut off at and-notice-undef, just a suggestion so that the URL doesn't get cut off. Maybe even removing the (too many) quotes. Or PHP: “Undefined variable/index/offset” notices – Funk Forty Niner Jan 20 '17 at 15:24 
2 
@Fred I guess an argument can be made for both variations. THere's a chance that newbies will enter the entire line, including the "Notice:" into their search query, which I'm sure is the main traffic generator for this question. If the messages are there in full, that's likely to improve visibility in search engines – Pekka 웃 Jan 20 '17 at 15:34 
up vote783down voteaccepted

Notice: Undefined variable

From the vast wisdom of the PHP Manual:

Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset()language construct can be used to detect if a variable has been already initialized. Additionally and more ideal is the solution of empty() since it does not generate a warning or error message if the variable is not initialized.

From PHP documentation:

No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.

This means that you could use only empty() to determine if the variable is set, and in addition it checks the variable against the following, 0,"",null.

Example:

$o = [];
@$var = ["",0,null,1,2,3,$foo,$o['myIndex']];
array_walk($var, function($v) {
    echo (!isset($v) || $v == false) ? 'true ' : 'false';
    echo ' ' . (empty($v) ? 'true' : 'false');
    echo "\n";
});

Test the above snippet in the 3v4l.org online PHP editor

Although PHP does not require a variable declaration, it does recommend it in order to avoid some security vulnerabilities or bugs where one would forget to give a value to a variable that will be used later in the script. What PHP does in the case of undeclared variables is issue a very low level error, E_NOTICE, one that is not even reported by default, but the Manual advises to allow during development.

Ways to deal with the issue:

  1. Recommended: Declare your variables, for example when you try to append a string to an undefined variable. Or use isset() / !empty() to check if they are declared before referencing them, as in:

    //Initializing variable
    $value = ""; //Initialization value; Examples
                 //"" When you want to append stuff later
                 //0  When you want to add numbers later
    //isset()
    $value = isset($_POST['value']) ? $_POST['value'] : '';
    //empty()
    $value = !empty($_POST['value']) ? $_POST['value'] : '';

    This has become much cleaner as of PHP 7.0, now you can use the null coalesce operator:

    // Null coalesce operator - No need to explicitly initialize the variable.
    $value = $_POST['value'] ?? '';
  2. Set a custom error handler for E_NOTICE and redirect the messages away from the standard output (maybe to a log file):

    set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)
  3. Disable E_NOTICE from reporting. A quick way to exclude just E_NOTICE is:

    error_reporting( error_reporting() & ~E_NOTICE )
  4. Suppress the error with the @ operator.

Note: It's strongly recommended to implement just point 1.

Notice: Undefined index / Undefined offset

This notice appears when you (or PHP) try to access an undefined index of an array.

Ways to deal with the issue:

  1. Check if the index exists before you access it. For this you can use isset() or array_key_exists():

    //isset()
    $value = isset($array['my_index']) ? $array['my_index'] : '';
    //array_key_exists()
    $value = array_key_exists('my_index', $array) ? $array['my_index'] : '';
  2. The language construct list() may generate this when it attempts to access an array index that does not exist:

    list($a, $b) = array(0 => 'a');
    //or
    list($one, $two) = explode(',', 'test string');

Two variables are used to access two array elements, however there is only one array element, index 0, so this will generate:

Notice: Undefined offset: 1

$_POST / $_GET / $_SESSION variable

The notices above appear often when working with $_POST$_GET or $_SESSION. For $_POSTand $_GET you just have to check if the index exists or not before you use them. For $_SESSIONyou have to make sure you have the session started with session_start() and that the index also exists.

Also note that all 3 variables are superglobals. This means they need to be written in uppercase.

Related:


728x90


Functionality:

Have created a simple browsing page navigation function. This is how the function should work:

1.) When a user click a "Start" button in page1, it will navigate the user to the 2nd page

2.) 2nd page is a games page whereby, upon navigation from the 1st page, a starting countdown timer will automatically display to notify the user that the game is starting in 3 seconds. Therefore, the display upon being navigated to page 2 should have 4 separate slides, each slides will display '3', '2', '1' and 'start'.

Hence I would like to ask for help how can I incorporate the fade-in counter code into my existing <script>??

Thanks

Code:

function fadeInCounter() {
  // Define "slides" and the "state" of the animation.
  var State = "Start1";
  // Global parameters for text.
  textSize(20);
  fill(139, 69, 19);

  var draw = function() {
    // Slide 1.
    if (State === "Start1") {
      background(205, 201, 201);
      text("3", 200, 200);
      Slide1 -= 5;
      if (Slide1 <= 0) {
        background(205, 201, 201);
        State = "Start2";
      }
    }
    // Slide 2.
    if (State === "Start2") {
      background(205, 201, 201);
      text("2", 200, 200);
      Slide2 -= 5;
      if (Slide2 <= 0) {
        background(205, 201, 201);
        State = "Start3";
      }
    }
    // Slide 3.
    if (State === "Start3") {
      background(205, 201, 201);
      text("1", 200, 200);
      Slide3 -= 5;
      if (Slide3 <= 0) {
        background(205, 201, 201);
        State = "End";
      }
    }

    // Ending frame.
    if (State === "End") {
      background(205, 201, 201);
      text("Start.", 180, 200);
    }
  };

}
<div id="page2" class="img-wrapper" align="center" style=" position: relative; background-image: url(Image/Page2.png); background-repeat: no-repeat; display: none; width: 100%;height: 100%;">

  <div id="fadeinCountDown"></div>


  <canvas id="canvas" width="300" height="300">
  </canvas>
  <canvas id="Counter" width="300" height="300">
  </canvas>
  <img id="roller" style="position:relative; top:1250px;" src="Image/Roller.png">
  <img id="scroll" style="position:absolute; top: 1250px; left: 380px; overflow-y: auto;" src="Image/Scroll.png">
</div>

shareimprove this question
   
where is the js code you have tried so far? can you set up a jsfiddle with your attempt too? – Lelio Faieta Nov 12 '15 at 9:28
   
@LelioFaieta I have added in what I have tried but I have no idea how to incorporate it in\. Please help – Luke Nov 12 '15 at 9:45

Following is a fade in/out timer. JSFiddle.

Also I have taken liberty to use single div instead of multiple divs.

var count = 3;

function updateTimer(){
    if(count > 0){
        $("#content").fadeOut('slow', function(){
        	$("#content").text(count);
            $("#content").fadeIn();
            count--;
        });
        
    }
    else if(count == 0){
        $("#content").fadeOut('slow', function(){
        	$("#content").text("Start");
            $("#content").fadeIn();
            count--;
        });
        
    }
    else {
    	$("#content").fadeOut();
        clearInterval(interval);
    }
    
}

var interval = setInterval(function(){updateTimer()},2000)
#content{
    font-size:26px;
    color:red;
    text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="content"></div>


728x90

자바스크립트에서 숫자를 표기할때 3자리마다 콤마를 찍어줘야 할 때가 있다 자주 사용하는 기능인데 매번 만들기란 여간 귀찮은게 아니다.

콤마찍기

1
2
3
4
5
//콤마찍기
function comma(str) {
    str = String(str);
    return str.replace(/(\d)(?=(?:\d{3})+(?!\d))/g, '$1,');
}

콤마풀기

1
2
3
4
5
//콤마풀기
function uncomma(str) {
    str = String(str);
    return str.replace(/[^\d]+/g, '');
}

복사 붙여넣기로 사용하자!

input box에서 사용자 입력시 바로 콤마를 찍어주기 위한 함수도 추가 한다.

1
2
3
4
5
function inputNumberFormat(obj) {
    obj.value = comma(uncomma(obj.value));
}
 
//<input type="text" onkeyup="inputNumberFormat(this)" />

 

728x90

안녕하세요. 오늘은 jQuery 스크립트를 사용해서

따라다니는 사이드바를 만들어 보겠습니다.


예전에 화면에 아예 고정되고 따라다니는 플로팅 메뉴를 만든적이 있긴한데

http://cocosoft.kr/149 - 플로팅메뉴(추천위젯,광고)

오늘은 사이드바의 메뉴 하나 또는 몇개만! 움직이는 따라다니면서 움직이는 형태를 알려드리겠습니다.


당연히 사용 전제 조건으로 jQuery 사용해야겠죠?

요즘 웬만한 스킨이나 티스토리 공식 반응형 웹 스킨등에서도 jQuery를 사용하고 있긴합니다.


완성된 예제 입니다.


스킨의 상관없이 기존 사이드바 div 태그에 값만 설정 추가 해주면

어느 사이드바에서도 사용이 가능합니다.

intro - 사이드바에 대한 고찰

요즘 티스토리에서도 반응형 웹스킨을 공식적으로 지원하고 있고


해외 포럼이나 해외 블로그, 반응형 사이트들을 살펴보면

모바일 디자인과 친화성을 위해서인지 1단 또는 2단형 반응형으로 개발 되는 경우가 많습니다.

구식 브라우저의 호환성도 높이고 깔끔한 디자인으로 포스트 본문에 집중도 잘 되는 것 같습니다.

아예 사이드바 카테고리를 숨겨놓거나 좌측이나 우측 사이드에 고정하는 방식을 많이 사용합니다.



해외 타임지 사이트도 사이드바만 따로 고정되어있는 형태고

티스토리 공식 반은형 스킨도 현재 2가지 형태를 제공하고 있습니다.


저도 이런 깔끔한 디자인이 마음에 들어서

아예 공식 스킨을 사용하거나 2단형식으로 바꿀까?도 고민중입니다.

하지만 이 형식의 단점도 존재합니다.

바로 고정된 사이드바에 광고를 게재시에 애드센스 광고 정책 위반이라는 점입니다.

position: fixed;형식으로 위치하게 되는데 이러한 사이드바 안에

광고를 집어넣게 되면 정책 위반으로 애드센스 수익과 계정이 정지 될 수 있습니다.


지금 티스토리 반응형 웹 공모전 이후 반응형 스킨들이 많이 퍼지면서

고정된 사이드바에 광고를 위치시키는 분들이 많은데

사이드바의 길이가 길어서 스크롤이 되어서 고정된 형태가 아닌 것 처럼 보여도

전부 정책 위반입니다. ㅠ_ㅠ 


저도 만약 사이드바의 애드센스 광고를 달지 않을 경우에는 해당 고정된 형태인 사이드바를 사용을 할 것 같습니다.

애드센스를 사용하시는 분들이라면 항상 정책 위반 ㅠ_ㅠ여부를 염두에 두고 해야합니다.

저도 스킨을 최근에 변경하면서 광고 정책을 위반하지 않으려고 스킨 여백 수정을 하고 있습니다.


만약 CCZ-CROSS 스킨 또는 티스토리 스킨을 사용하시는 분들중


우측이나 좌측에 고정된 형태의 사이드바를 사용하고 싶으신 분들은

SONYLOVE님의 게시글을 참고하세요!

http://sonylove.tistory.com/1132 - 티스토리 스킨 사이드바 고정하는 방법


본격적으로 시작!!!!!!!

이제 본격적으로 사이드바의 메뉴중

하나 또는 여러개만 스크롤을 내릴시 본문콘텐츠에 맞춰서

따라 내려가는 방법에 대해서 알아보겠습니다.

부드럽게 따라다니는 사이드바

우선 자바스크립트 소스를 붙혀넣기 해야됩니다.

해당소스는 http://blog.bits.kr/90 및 http://madebykaus.com/?p=300 를 참고해서

티스토리 블로그에 맞게 수정을 하였으며, 더자세한 속성값은 해당 포스트를 참고바랍니다.


html//css 수정에서 html 제일 하단 부분 </body> 에 붙혀넣기를 하면됩니다.

Markup

<script>
$(function(){
    var $win = $(window);
    var top = $(window).scrollTop(); // 현재 스크롤바의 위치값을 반환합니다.
 
    /*사용자 설정 값 시작*/
    var speed          = 500;     // 따라다닐 속도 : "slow", "normal", or "fast" or numeric(단위:msec)
    var easing         = 'linear'; // 따라다니는 방법 기본 두가지 linear, swing
    var $layer         = $('.float_sidebar'); // 레이어 셀렉팅
    var layerTopOffset = 0;   // 레이어 높이 상한선, 단위:px
    $layer.css('position', 'relative').css('z-index', '1');
    /*사용자 설정 값 끝*/
 
    // 스크롤 바를 내린 상태에서 리프레시 했을 경우를 위해
    if (top > 0 )
        $win.scrollTop(layerTopOffset+top);
    else
        $win.scrollTop(0);
 
    //스크롤이벤트가 발생하면
    $(window).scroll(function(){
        yPosition = $win.scrollTop() - 1100; //이부분을 조정해서 화면에 보이도록 맞추세요
        if (yPosition < 0)
        {
            yPosition = 0;
        }
        $layer.animate({"top":yPosition }, {duration:speed, easing:easing, queue:false});
    });
});
</script>
</body>
</html>

그리고 나서 따라다니게 하고 싶은 사이드바 모듈에

클래스 값 .float_sidebar을 넣어주면 됩니다.

Markup

<div class="float_sidebar"></div>

요런식으로 추가해도 됩니다!!


스크립트 부분에서 yPosition 수치만 잘 조절해주시면 쉽게 따라오는 메뉴를 만들 수 있습니다.

따라다니는 사이드바 메뉴도 마찬가지로 애드센스 영역을 따라다니게 해서는 안됩니다. 애드센스 광고 정책 위반입니다.


+추가 응용편)일정이상 내려가면 나타나게하기

위 방법은 사이드바 중간에 위치한 모듈도 클래스 값을 줘서 내릴 경우

사이드바의 위치 깨짐이 없이 내려가게 가능하나

보기에는 좋지 않겠죠?!ㅎㅎ

다른 사이드바 모듈을 다거치면서 내려오니깐요?


그래서 되도록이면 따라다니는 사이드바를 가장 아래 쪽으로 위치해주거나


아니면 일정 스크롤 이상 내려갔을 경우 나타나게 만들어 주면 되겠죠??

동일한 사이드바를 하나더 만들어서 가장 아래에 배치를 해주고

속성값은 display: none; 값을 줘서 보이지 않게 한 다음


아래 스크립트를 추가해서 일정 이상 내려갔을 경우 나타나게 해주면 되겠죠?


Markup

<script>
$(document).ready(function() {
    $(window).scroll(function() {
        $(this).scrollTop() > 1000 ? $(".float_sidebar").fadeIn() : $(".float_sidebar").fadeOut()
    })
});
</script>


따라다니는 사이드바 메뉴 배너 플로팅 박스들 만드는 방법은 다양하니!!

잘 참고하시면 될 것같아요.

이 방법을 응용 하시면 다양한 연출이 가능 할 것 같습니다.


굳이 부드럽게 이동하는 것을 원하지 않는 분들은 addClassremoveClass잘 사용하셔도

position:와 여백을 수정하게 해서!

고정되어 이동하는 카테고리를 잘 만들 수 있을 거라 생각합니다!!

Markup

<script>
	$(document).ready(function () {  
        var top = $('#float_sidebar').offset().top - parseFloat($('#float_sidebar').css('marginTop').replace(/auto/, 0));
        $(window).scroll(function (event) {
        var y = $(this).scrollTop();
  
       if (y >= top) {
          $('#float_sidebar').addClass('fixed');
       } else {
          $('#float_sidebar').removeClass('fixed');
      }
  });
});
</script>

이런식으로 말이죠.

결론

저도 지금 스킨을 바꾸면서 계속 수정을 하고 변경을 하고 있는 중입니다.

아예 사이드바를 고정할지

아니면 스크롤이 내리더라도 따라다니는 메뉴를 사용해서

 블로그 콘텐츠의 접근성을 높히는 방법을 사용할지


따로 addthis와 같은 추천글 플러그인을 사용해서 사용할지

(addthis는 유로 구매가 아니면 ㅠ 특정 추천글을 선택할 수 없는 아쉬움이 있습니다.)


계속 테스트를 해보고 결정을 해야 할 것 같습니다.

보조 블로그는 최신글 목록만 따라다는 사이드바를 적용 했는데

애드센스의 페이지 RPM이 소폭 증가 한 것을 알 수 있었습니다.


이것 때문이지는 모르겠지만 사이드바의 영역에 어느정도 추천 콘텐츠를 제공하는 것은

 방문객의 페이지 재방문을 조금이나마 높혀줄 수 있다고 생각합니다.!


그럼 다들 블로그에 사이드바 꾸미기를 잘하길 바라겠습니다.



출처: http://cocosoft.kr/361 [코코소프트]

출처: http://cocosoft.kr/361 [코코소프트]

출처: http://cocosoft.kr/361 [코코소프트]

출처: http://cocosoft.kr/361 [코코소프트]

+ Recent posts