Header Ads

PHP 변수관련 함수 정리


/*
변수의 데이터타입을 반환
gettype
string = gettype(mixed_var)
http://php.net/manual/en/function.gettype.php
*/
$data = array(1, 1.0, NULL, new stdClass, 'foo');

foreach ($data as $value) {
    echo gettype($value), " / ";
}

/*
변수가 boolean 타입 변수인지 여부를 반환
is_bool
bool = is_bool(mixed_var)
http://php.net/manual/en/function.is-bool.php
*/
$a = false;
$b = 0;
// Since $a is a boolean, it will return true
if (is_bool($a) === true) {
    echo "Yes, this is a boolean";
}
// Since $b is not a boolean, it will return false
if (is_bool($b) === false) {
    echo "No, this is not a boolean";
}

/*
변수가 부동소수형 타입의 변수인지 여부를 반환
is_float, is_double, is_real
bool = is_float(mixed_var)
http://php.net/manual/en/function.is-float.php
http://php.net/manual/en/function.is-double.php
http://php.net/manual/en/function.is-real.php
*/
if (is_float(27.25)) {
    echo "is float";
} else {
    echo "is not float";
}
var_dump(is_float('abc')); // bool(false)
var_dump(is_float(23));    // bool(false)
var_dump(is_float(23.5));  // bool(true)
var_dump(is_float(1e7));   // bool(true) Scientific Notation
var_dump(is_float(true));  // bool(false)

/*
변수의 값이 숫자인지 여부를 반환
is_numeric
bool = is_numeric(mixed_var)
http://php.net/manual/en/function.is-numeric.php
*/
$tests = array(
    "42",
    1337,
    0x539,
    02471,
    0b10100111001,
    1337e0,
    "not numeric",
    array(),
    9.1
);
foreach ($tests as $element) {
    if (is_numeric($element)) {
        echo "'{$element}' is numeric";
    } else {
        echo "'{$element}' is NOT numeric";
    }
}

/*
변수가 문자열 타입의 변수인지 여부를 반환
is_string
bool = is_string(mixed_var)
http://php.net/manual/en/function.is-string.php
*/
$values = array(false, true, null, 'abc', '23', 23, '23.5', 23.5, '', ' ', '0', 0);
foreach ($values as $value) {
    echo "is_string(";
    var_export($value);
    echo ") = ";
    echo var_dump(is_string($value));
}

/*
변수가 배열인지 여부를 반환
is_array
bool = is_array(mixed_var)
http://php.net/manual/en/function.is-array.php
*/
$yes = array('this', 'is', 'an array');
$no  = 'this is a string';
echo is_array($yes) ? 'Array' : 'not an Array';
echo is_array($no) ? 'Array' : 'not an Array';

/*
변수가 클래스의 객체인지 여부를 반환
is_object
bool = is_object(mixed_var)
http://php.net/manual/en/function.is-object.php
*/
function get_students($obj)
{
    if (!is_object($obj)) {
        return false;
    }

    return $obj->students;
}
$obj = new stdClass();
$obj->students = array('Kalle', 'Ross', 'Felipe');
var_dump(get_students(null)); // bool(false)
var_dump(get_students($obj)); // array(3)

/*
변수가 리소스 타입의 변수인지 여부를 반환
is_resource
bool = is_resource ( mixed $var )
http://php.net/manual/en/function.is-resource.php
*/
$db_link = @mysql_connect('localhost', 'mysql_user', 'mysql_pass');
if (!is_resource($db_link)) {
    die('Can\'t connect : ' . mysql_error());
}

/*
변수가 NULL 값인지 여부를 반환
is_null
bool = is_null ( mixed $var )
http://php.net/manual/en/function.is-null.php
*/
error_reporting(E_ALL);
$foo = NULL;
var_dump(is_null($inexistent), is_null($foo));

/*
변수가 스칼라 타입의 변수인지 여부를 반환
is_scalar
bool = is_scalar ( mixed $var )
http://php.net/manual/en/function.is-scalar.php
*/
function show_var($var) 
{
    if (is_scalar($var)) {
        echo $var;
    } else {
        var_dump($var);
    }
}
$pi = 3.1416;
$proteins = array("hemoglobin", "cytochrome c oxidase", "ferredoxin");

show_var($pi);
show_var($proteins);

/*
변수의 정수형 값을 반환
intval
int = intval ( mixed $var [, int $base = 10 ] )
http://php.net/manual/en/function.intval.php
*/
echo intval(42);                      // 42
echo intval(4.2);                     // 4
echo intval('42');                    // 42
echo intval('+42');                   // 42
echo intval('-42');                   // -42
echo intval(042);                     // 34
echo intval('042');                   // 42
echo intval(1e10);                    // 1410065408
echo intval('1e10');                  // 1
echo intval(0x1A);                    // 26
echo intval(42000000);                // 42000000
echo intval(420000000000000000000);   // 0
echo intval('420000000000000000000'); // 2147483647
echo intval(42, 8);                   // 42
echo intval('42', 8);                 // 34
echo intval(array());                 // 0
echo intval(array('foo', 'bar'));     // 1

/*
변수의 부동소수형 값을 반환
floatval, doubleval
float = floatval ( mixed $var )
http://php.net/manual/en/function.floatval.php
http://php.net/manual/en/function.doubleval.php
*/
$var = '122.34343The';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343

$var = 'The122.34343';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 0

/*
변수의 값을 문자열 형태로 반환
strval
string = strval ( mixed $var )
http://php.net/manual/en/function.strval.php
*/
class StrValTest
{
    public function __toString()
    {
        return __CLASS__;
    }
}
// Prints 'StrValTest'
echo strval(new StrValTest);

/*
변수가 어떤 값으로 설정되어 존재하는지 여부를 검사
isset
bool = isset ( mixed $var [, mixed $... ] )
http://php.net/manual/en/function.isset.php
*/
$var = '';

// This will evaluate to TRUE so the text will be printed.
if (isset($var)) {
    echo "This var is set so I will print.";
}

// In the next examples we'll use var_dump to output
// the return value of isset().

$a = "test";
$b = "anothertest";

var_dump(isset($a));      // TRUE
var_dump(isset($a, $b)); // TRUE

unset ($a);

var_dump(isset($a));     // FALSE
var_dump(isset($a, $b)); // FALSE

$foo = NULL;
var_dump(isset($foo));   // FALSE

$a = array ('test' => 1, 'hello' => NULL, 'pie' => array('a' => 'apple'));

var_dump(isset($a['test']));            // TRUE
var_dump(isset($a['foo']));             // FALSE
var_dump(isset($a['hello']));           // FALSE

// The key 'hello' equals NULL so is considered unset
// If you want to check for NULL key values then try: 
var_dump(array_key_exists('hello', $a)); // TRUE

// Checking deeper array values
var_dump(isset($a['pie']['a']));        // TRUE
var_dump(isset($a['pie']['b']));        // FALSE
var_dump(isset($a['cake']['a']['b']));  // FALSE

$expected_array_got_string = 'somestring';
var_dump(isset($expected_array_got_string['some_key']));
var_dump(isset($expected_array_got_string[0]));
var_dump(isset($expected_array_got_string['0']));
var_dump(isset($expected_array_got_string[0.5]));
var_dump(isset($expected_array_got_string['0.5']));
var_dump(isset($expected_array_got_string['0 Mostel']));


/*
변수를 파괴
unset
void = unset ( mixed $var [, mixed $... ] )
http://php.net/manual/en/function.unset.php
*/
function destroy_foo() 
{
    global $foo;
    unset($foo);
}

$foo = 'bar';
destroy_foo();
echo $foo;

function foo() 
{
    unset($GLOBALS['bar']);
}

$bar = "something";
foo();

function foo(&$bar) 
{
    unset($bar);
    $bar = "blah";
}

$bar = 'something';
echo "$bar";

foo($bar);
echo "$bar";

function foo()
{
    static $bar;
    $bar++;
    echo "Before unset: $bar, ";
    unset($bar);
    $bar = 23;
    echo "after unset: $bar";
}

foo();
foo();
foo();


/*
변수가 비어있는 값을 가진 변수인지 여부를 반환
empty
bool = empty ( mixed $var )
http://php.net/manual/en/function.empty.php
*/
$var = 0;

// Evaluates to true because $var is empty
if (empty($var)) {
    echo '$var is either 0, empty, or not set at all';
}

// Evaluates as true because $var is set
if (isset($var)) {
    echo '$var is set even though it is empty';
}

$expected_array_got_string = 'somestring';
var_dump(empty($expected_array_got_string['some_key']));
var_dump(empty($expected_array_got_string[0]));
var_dump(empty($expected_array_got_string['0']));
var_dump(empty($expected_array_got_string[0.5]));
var_dump(empty($expected_array_got_string['0.5']));
var_dump(empty($expected_array_got_string['0 Mostel']));

/*
변수의 정보를 이해하기 쉬운 형태로 출력
print_r
mixed = print_r ( mixed $expression [, bool $return = false ] )
http://php.net/manual/en/function.print-r.php
*/
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
$b = array ('m' => 'monkey', 'foo' => 'bar', 'x' => array ('x', 'y', 'z'));
$results = print_r($b, true); // $results now contains output from print_r

/*
변수에 대한 구조화된 정보를 출력
var_dump
void = var_dump ( mixed $expression [, mixed $... ] )
http://php.net/manual/en/function.var-dump.php
*/
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);

$b = 3.1;
$c = true;
var_dump($b, $c);


/*
변수에 대한 구조화된 정보를 PHP 코드의 형태로 출력 또는 반환
var_export
mixed = var_export ( mixed $expression [, bool $return = false ] )
http://php.net/manual/en/function.var-export.php
*/
$a = array (1, 2, array ("a", "b", "c"));
var_export($a);
$b = 3.1;
$v = var_export($b, true);
echo $v;

class A { public $var; }
$a = new A;
$a->var = 5;
var_export($a);

class A
{
    public $var1;
    public $var2;

    public static function __set_state($an_array)
    {
        $obj = new A;
        $obj->var1 = $an_array['var1'];
        $obj->var2 = $an_array['var2'];
        return $obj;
    }
}

$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';

eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
                                            //    'var1' => 5,
                                            //    'var2' => 'foo',
                                            // ));
var_dump($b);

/*
인자로 전달받은 변수의 데이터를 저장 및 복원이 가능한 형태로 반환
serialize
string = serialize ( mixed $value )
http://php.net/manual/en/function.serialize.php
*/
// $session_data contains a multi-dimensional array with session
// information for the current user.  We use serialize() to store
// it in a database at the end of the request.

$conn = odbc_connect("localhost", "db_user", "db_password");
$stmt = odbc_prepare($conn,
      "UPDATE sessions SET data = ? WHERE id = ?");
$sqldata = array (serialize($session_data), $_SERVER['PHP_AUTH_USER']);
if (!odbc_execute($stmt, $sqldata)) {
    $stmt = odbc_prepare($conn,
     "INSERT INTO sessions (id, data) VALUES(?, ?)");
    if (!odbc_execute($stmt, $sqldata)) {
        /* Something went wrong.. */
    }
}

/*
변환되었던 데이터를 원래의 데이터로 복원
unserialize
mixed = unserialize ( string $str )
http://php.net/manual/en/function.unserialize.php
*/
// Here, we use unserialize() to load session data to the
// $session_data array from the string selected from a database.
// This example complements the one described with serialize().

$conn = odbc_connect("localhost", "db_user", "db_password");
$stmt = odbc_prepare($conn, "SELECT data FROM sessions WHERE id = ?");
$sqldata = array($_SERVER['PHP_AUTH_USER']);
if (!odbc_execute($stmt, $sqldata) || !odbc_fetch_into($stmt, $tmp)) {
    // if the execute or fetch fails, initialize to empty array
    $session_data = array();
} else {
    // we should now have the serialized data in $tmp[0].
    $session_data = unserialize($tmp[0]);
    if (!is_array($session_data)) {
        // something went wrong, initialize to empty array
        $session_data = array();
    }
}

$serialized_object='O:1:"a":1:{s:5:"value";s:3:"100";}';

// unserialize_callback_func directive available as of PHP 4.2.0
ini_set('unserialize_callback_func', 'mycallback'); // set your callback_function

function mycallback($classname) 
{
    // just include a file containing your classdefinition
    // you get $classname to figure out which classdefinition is required
}

No comments

Copyright 2016, minki. All rights reserved. Powered by Blogger.