Chillax in dev

[php] 원하는 데이터 찾기 strpos(), in_array() 본문

PHP & MySQL

[php] 원하는 데이터 찾기 strpos(), in_array()

Seong Story 2023. 1. 30. 13:28
728x90

 원하는 데이터 찾기 strpos(), in_array()

- 매번 원하는 데이터를 찾을 때 자주 검색해 보게 되는 strpos() , in_array()는 PHP개발 중 거의 매일 사용하는 함수들이다. 

이런 함수는 외워주면 좋습니다.

 

strpos() : 문자열에서 내가 원하는 값이 있나 확인하는 함수

사용 예시

<?php 
$string_data = 'hello world';
$find_data = 'hello';
$pos = strpos($string_data, $find_data);

//반환
if($pos !== false){
	//찾는 문자열데이터를 포함합니다.
	echo "Y";
}else{
	//찾는 문자열데이터를 찾지 못했습니다.
	echo "N";
}
?>

설명

- PHP 메뉴얼에서 검색해 보면 strpos() 함수의 원형은 이렇습니다. 

 

https://www.php.net/manual/en/function.strpos.php

 

PHP: strpos - Manual

A pair of functions to replace every nth occurrence of a string with another string, starting at any position in the haystack. The first works on a string and the second works on a single-level array of strings, treating it as a single string for replaceme

www.php.net

반환 부분을 살펴보면 true, false, 숫자 0 도 반환 할 수 있기 때문에 엄격한 연산자인 ===,!===를 활용합니다.

왼쪽 피연산자와 오른쪽 피연산자가 같고, 같은 타입일 경우 true 반환합니다.

 

in_array() : 값이 배열 안에 존재하는지 확인하는 함수

사용 예시 

<?php 
$arr_data = array("apple", "orange", "lemon");
$find_date = "lemon";

if(isset($find_date) && $find_date != "" && $find_date != null && in_array($find_date,$arr_data)){
    //찾는 문자열이 배열에 포함됨
    echo "Y";
}else{
    //찾는 문자열이 배열에 없음
    echo "N";
}

?>

- 설명

이런 분기분을 활용할떄 확인할 데이터가 유효한지  isset()으로 확인 후 null이 아니고 "빈값"이 아닌 경우 확인합니다.

in_array( 확인할 값, 배열) 형식으로 포함되면 true를 반환합니다. 

역시 php 메뉴얼을 확인하면 이렇습니다.

https://www.php.net/manual/en/function.in-array.php

 

PHP: in_array - Manual

Loose checking returns some crazy, counter-intuitive results when used with certain arrays. It is completely correct behaviour, due to PHP's leniency on variable types, but in "real-life" is almost useless.The solution is to use the strict checking option.

www.php.net

 

정리 

- 문자열에서 원하는 문자포함되는지 확인할 땐 strpos($전체 문장, $찾을 문자) , 배열에서 원하는 문자열 데이터가 포함되는지 확인할 땐 in_array($배열, $찾을 문자)를 활용합시다.

 

- php 함수는 php.net Documentation에 검색이 잘 설명되어있고 가장 정확합니다. 자주 사용하는 함수는 검색해서 정확히 알고 쓰는 습관을 들이면 좋겠습니다. 

 

감사합니다 :)

728x90
LIST
Comments