Php array element type

gettype

Returns the type of the PHP variable value . For type checking, use is_* functions.

Parameters

The variable being type checked.

Return Values

  • «boolean»
  • «integer»
  • «double» (for historical reasons «double» is returned in case of a float , and not simply «float» )
  • «string»
  • «array»
  • «object»
  • «resource»
  • «resource (closed)» as of PHP 7.2.0
  • «NULL»
  • «unknown type»

Changelog

Version Description
7.2.0 Closed resources are now reported as ‘resource (closed)’ . Previously the returned value for closed resources were ‘unknown type’ .

Examples

Example #1 gettype() example

$data = array( 1 , 1. , NULL , new stdClass , ‘foo’ );

foreach ( $data as $value ) echo gettype ( $value ), «\n» ;
>

The above example will output something similar to:

integer double NULL object string

See Also

  • get_debug_type() — Gets the type name of a variable in a way that is suitable for debugging
  • settype() — Set the type of a variable
  • get_class() — Returns the name of the class of an object
  • is_array() — Finds whether a variable is an array
  • is_bool() — Finds out whether a variable is a boolean
  • is_callable() — Verify that a value can be called as a function from the current scope.
  • is_float() — Finds whether the type of a variable is float
  • is_int() — Find whether the type of a variable is integer
  • is_null() — Finds whether a variable is null
  • is_numeric() — Finds whether a variable is a number or a numeric string
  • is_object() — Finds whether a variable is an object
  • is_resource() — Finds whether a variable is a resource
  • is_scalar() — Finds whether a variable is a scalar
  • is_string() — Find whether the type of a variable is string
  • function_exists() — Return true if the given function has been defined
  • method_exists() — Checks if the class method exists
Читайте также:  Очистить массив от дублей php

User Contributed Notes 2 notes

Be careful comparing ReflectionParameter::getType() and gettype() as they will not return the same results for a given type.

string — string // OK
int — integer // Type mismatch
bool — boolean // Type mismatch
array — array // OK

Same as for «boolean» below, happens with integers. gettype() return «integer» yet proper type hint is «int».

If your project is PHP8+ then you should consider using get_debug_type() instead which seems to return proper types that match used for type hints.

Источник

Php – Determine the type of array element in php

I am calling a function that returns the an array. A for loop iteration gives the following output.

string(22) «text/xml;charset=UTF-8»

string(7) «chunked»

string(4) «gzip»

array(2) < ["Expect"]=>string(12) «100-continue» [«Content-Type»]=>
string(48) «application/x-www-form-urlencoded; charset=utf-8» >

object(CFSimpleXML)#10 (1) < [0]=>string(6) «123456» >

How can i check whether an array element is an object or string ?

Best Solution

foreach ($array as $element) < if (is_array($element)) < // array >else if (is_string($element)) < // string >else if (is_int($element)) < // int >else if (is_float($element)) < // float >else if (is_bool($element)) < // bool >else if (is_object($element)) < // object >else if (is_resource($element)) < // resource >else < // null/invalid type (you could add an === NULL if you want, I suppose) >> 

There is also get_type() and the typeof operator, but since these return strings that may be subject to change in some future PHP version, the is_*() functions are more reliable.

Php – How to prevent SQL injection in PHP

The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create SQL statement with correctly formatted data parts, but if you don’t fully understand the details, you should always use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.

You basically have two options to achieve this:

    Using PDO (for any supported database driver):

 $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name'); $stmt->execute([ 'name' => $name ]); foreach ($stmt as $row) < // Do something with $row >
 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?'); $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string' $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) < // Do something with $row >

If you’re connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, pg_prepare() and pg_execute() for PostgreSQL). PDO is the universal option.

Correctly setting up the connection

Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:

$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'password'); $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

In the above example the error mode isn’t strictly necessary, but it is advised to add it. This way the script will not stop with a Fatal Error when something goes wrong. And it gives the developer the chance to catch any error(s) which are throw n as PDOException s.

What is mandatory, however, is the first setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren’t parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).

Although you can set the charset in the options of the constructor, it’s important to note that ‘older’ versions of PHP (before 5.3.6) silently ignored the charset parameter in the DSN.

Explanation

The SQL statement you pass to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. Then when you call execute , the prepared statement is combined with the parameter values you specify.

The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn’t intend.

Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains ‘Sarah’; DELETE FROM employees the result would simply be a search for the string «‘Sarah’; DELETE FROM employees» , and you will not end up with an empty table.

Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.

Oh, and since you asked about how to do it for an insert, here’s an example (using PDO):

$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)'); $preparedStatement->execute([ 'column' => $unsafeValue ]); 

Can prepared statements be used for dynamic queries?

While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.

For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.

// Value whitelist // $dir can only be 'DESC', otherwise it will be 'ASC' if (empty($dir) || $dir !== 'DESC')
Php – Deleting an element from an array in PHP

There are different ways to delete an array element, where some are more useful for some specific tasks than others.

Deleting a single array element

If you want to delete just one array element you can use unset() or alternatively \array_splice() .

If you know the value and don’t know the key to delete the element you can use \array_search() to get the key. This only works if the element does not occur more than once, since \array_search returns the first hit only.

unset()

Note that when you use unset() the array keys won’t change. If you want to reindex the keys you can use \array_values() after unset() , which will convert all keys to numerically enumerated keys starting from 0.

$array = [0 => "a", 1 => "b", 2 => "c"]; unset($array[1]); // ↑ Key which you want to delete 

\array_splice() method

If you use \array_splice() the keys will automatically be reindexed, but the associative keys won’t change — as opposed to \array_values() , which will convert all keys to numerical keys.

\array_splice() needs the offset, not the key, as the second parameter.

$array = [0 => "a", 1 => "b", 2 => "c"]; \array_splice($array, 1, 1); // ↑ Offset which you want to delete 

array_splice() , same as unset() , take the array by reference. You don’t assign the return values of those functions back to the array.

Deleting multiple array elements

If you want to delete multiple array elements and don’t want to call unset() or \array_splice() multiple times you can use the functions \array_diff() or \array_diff_key() depending on whether you know the values or the keys of the elements which you want to delete.

\array_diff() method

If you know the values of the array elements which you want to delete, then you can use \array_diff() . As before with unset() it won’t change the keys of the array.

$array = [0 => "a", 1 => "b", 2 => "c", 3 => "c"]; $array = \array_diff($array, ["a", "c"]); // └────────┘ // Array values which you want to delete 

\array_diff_key() method

If you know the keys of the elements which you want to delete, then you want to use \array_diff_key() . You have to make sure you pass the keys as keys in the second parameter and not as values. Keys won’t reindex.

$array = [0 => "a", 1 => "b", 2 => "c"]; $array = \array_diff_key($array, [0 => "xy", "2" => "xy"]); // ↑ ↑ // Array keys which you want to delete 

If you want to use unset() or \array_splice() to delete multiple elements with the same value you can use \array_keys() to get all the keys for a specific value and then delete all elements.

Related Question

Источник

gettype

Returns the type of the PHP variable value . For type checking, use is_* functions.

Parameters

The variable being type checked.

Return Values

  • «boolean»
  • «integer»
  • «double» (for historical reasons «double» is returned in case of a float , and not simply «float» )
  • «string»
  • «array»
  • «object»
  • «resource»
  • «resource (closed)» as of PHP 7.2.0
  • «NULL»
  • «unknown type»

Changelog

Version Description
7.2.0 Closed resources are now reported as ‘resource (closed)’ . Previously the returned value for closed resources were ‘unknown type’ .

Examples

Example #1 gettype() example

$data = array( 1 , 1. , NULL , new stdClass , ‘foo’ );

foreach ( $data as $value ) echo gettype ( $value ), «\n» ;
>

The above example will output something similar to:

integer double NULL object string

See Also

  • get_debug_type() — Gets the type name of a variable in a way that is suitable for debugging
  • settype() — Set the type of a variable
  • get_class() — Returns the name of the class of an object
  • is_array() — Finds whether a variable is an array
  • is_bool() — Finds out whether a variable is a boolean
  • is_callable() — Verify that a value can be called as a function from the current scope.
  • is_float() — Finds whether the type of a variable is float
  • is_int() — Find whether the type of a variable is integer
  • is_null() — Finds whether a variable is null
  • is_numeric() — Finds whether a variable is a number or a numeric string
  • is_object() — Finds whether a variable is an object
  • is_resource() — Finds whether a variable is a resource
  • is_scalar() — Finds whether a variable is a scalar
  • is_string() — Find whether the type of a variable is string
  • function_exists() — Return true if the given function has been defined
  • method_exists() — Checks if the class method exists

User Contributed Notes 2 notes

Be careful comparing ReflectionParameter::getType() and gettype() as they will not return the same results for a given type.

string — string // OK
int — integer // Type mismatch
bool — boolean // Type mismatch
array — array // OK

Same as for «boolean» below, happens with integers. gettype() return «integer» yet proper type hint is «int».

If your project is PHP8+ then you should consider using get_debug_type() instead which seems to return proper types that match used for type hints.

Источник

Оцените статью