728x90

Example

Alert a text when an <input> field is changed:

$("input").change(function(){
    alert("The text has been changed.");
});
Try it Yourself »

Definition and Usage

The change event occurs when the value of an element has been changed (only works on <input>, <textarea> and <select> elements).

The change() method triggers the change event, or attaches a function to run when a change event occurs.

Note: For select menus, the change event occurs when an option is selected. For text fields or text areas, the change event occurs when the field loses focus, after the content has been changed.


Syntax

Trigger the change event for the selected elements:

$(selector).change()Try it

Attach a function to the change event:

$(selector).change(function)Try it


ParameterDescription
functionOptional. Specifies the function to run when the change event occurs for the selected elements



jQuery Change 이벤트에서 input, textarea 에서 change 가 trigger 되는 경우는, 해당 박스의 데이터가 바뀌고 나서 포인터가 다른곳으로 눌러졌을때 발동된다. (즉 그 칸안에 있으면 안된다는 소리다)

728x90

(PHP 5, PHP 7)

mysqli::real_escape_string -- mysqli_real_escape_string — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

Description ¶

Object oriented style

string mysqli::escape_string ( string $escapestr )
string mysqli::real_escape_string ( string $escapestr )

Procedural style

string mysqli_real_escape_string ( mysqli $link , string $escapestr )

This function is used to create a legal SQL string that you can use in an SQL statement. The given string is encoded to an escaped SQL string, taking into account the current character set of the connection.

Caution

Security: the default character set

The character set must be set either at the server level, or with the API function mysqli_set_charset() for it to affect mysqli_real_escape_string(). See the concepts section on character sets for more information.

Parameters ¶

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

escapestr

The string to be escaped.

Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.

Return Values ¶

Returns an escaped string.

Errors/Exceptions ¶

Executing this function without a valid MySQLi connection passed in will return NULL and emit E_WARNING level errors.

Examples ¶

Example #1 mysqli::real_escape_string() example

Object oriented style

<?php
$mysqli 
= new mysqli("localhost""my_user""my_password""world");

/* check connection */
if (mysqli_connect_errno()) {
    
printf("Connect failed: %s\n"mysqli_connect_error());
    exit();
}

$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City");

$city "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!$mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
    
printf("Error: %s\n"$mysqli->sqlstate);
}

$city $mysqli->real_escape_string($city);

/* this query with escaped $city will work */
if ($mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
    
printf("%d Row inserted.\n"$mysqli->affected_rows);
}

$mysqli->close();
?>

Procedural style

<?php
$link 
mysqli_connect("localhost""my_user""my_password""world");

/* check connection */
if (mysqli_connect_errno()) {
    
printf("Connect failed: %s\n"mysqli_connect_error());
    exit();
}

mysqli_query($link"CREATE TEMPORARY TABLE myCity LIKE City");

$city "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!mysqli_query($link"INSERT into myCity (Name) VALUES ('$city')")) {
    
printf("Error: %s\n"mysqli_sqlstate($link));
}

$city mysqli_real_escape_string($link$city);

/* this query with escaped $city will work */
if (mysqli_query($link"INSERT into myCity (Name) VALUES ('$city')")) {
    
printf("%d Row inserted.\n"mysqli_affected_rows($link));
}

mysqli_close($link);
?>

The above examples will output:

Error: 42000
1 Row inserted.

Notes ¶

Note:

For those accustomed to using mysql_real_escape_string(), note that the arguments of mysqli_real_escape_string() differ from what mysql_real_escape_string() expects. The link identifier comes first in mysqli_real_escape_string(), whereas the string to be escaped comes first in mysql_real_escape_string().

See Also ¶

add a note add a note

User Contributed Notes 12 notes

tobias_demuth at web dot de ¶
12 years ago
Note, that if no connection is open, mysqli_real_escape_string() will return an empty string!
Josef Toman ¶
7 years ago
For percent sign and underscore I use this:
<?php
$more_escaped 
addcslashes($escaped'%_');
?>
therselman at gmail dot com ¶
5 months ago
Presenting several UTF-8 / Multibyte-aware escape functions.

These functions represent alternatives to mysqli::real_escape_string, as long as your DB connection and Multibyte extension are using the same character set (UTF-8), they will produce the same results by escaping the same characters as mysqli::real_escape_string.

This is based on research I did for my SQL Query Builder class:
https://github.com/twister-php/sql

<?php
/**
* Returns a string with backslashes before characters that need to be escaped.
* As required by MySQL and suitable for multi-byte character sets
* Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and ctrl-Z.
*
* @param string $string String to add slashes to
* @return $string with `\` prepended to reserved characters 
*
* @author Trevor Herselman
*/
if (function_exists('mb_ereg_replace'))
{
    function 
mb_escape(string $string)
    {
        return 
mb_ereg_replace('[\x00\x0A\x0D\x1A\x22\x27\x5C]''\\\0'$string);
    }
} else {
    function 
mb_escape(string $string)
    {
        return 
preg_replace('~[\x00\x0A\x0D\x1A\x22\x27\x5C]~u''\\\$0'$string);
    }
}

?>

Characters escaped are (the same as mysqli::real_escape_string):

00 = \0 (NUL)
0A = \n
0D = \r
1A = ctl-Z
22 = "
27 = '
5C = \

Note: preg_replace() is in PCRE_UTF8 (UTF-8) mode (`u`).

Enhanced version:

When escaping strings for `LIKE` syntax, remember that you also need to escape the special characters _ and %

So this is a more fail-safe version (even when compared to mysqli::real_escape_string, because % characters in user input can cause unexpected results and even security violations via SQL injection in LIKE statements):

<?php

/**
* Returns a string with backslashes before characters that need to be escaped.
* As required by MySQL and suitable for multi-byte character sets
* Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and ctrl-Z.
* In addition, the special control characters % and _ are also escaped,
* suitable for all statements, but especially suitable for `LIKE`.
*
* @param string $string String to add slashes to
* @return $string with `\` prepended to reserved characters 
*
* @author Trevor Herselman
*/
if (function_exists('mb_ereg_replace'))
{
    function 
mb_escape(string $string)
    {
        return 
mb_ereg_replace('[\x00\x0A\x0D\x1A\x22\x25\x27\x5C\x5F]''\\\0'$string);
    }
} else {
    function 
mb_escape(string $string)
    {
        return 
preg_replace('~[\x00\x0A\x0D\x1A\x22\x25\x27\x5C\x5F]~u''\\\$0'$string);
    }
}

?>

Additional characters escaped:

25 = %
5F = _

Bonus function:

The original MySQL `utf8` character-set (for tables and fields) only supports 3-byte sequences.
4-byte characters are not common, but I've had queries fail to execute on 4-byte UTF-8 characters, so you should be using `utf8mb4` wherever possible.

However, if you still want to use `utf8`, you can use the following function to replace all 4-byte sequences.

<?php
// Modified from: https://stackoverflow.com/a/24672780/2726557
function mysql_utf8_sanitizer(string $str)
{
    return 
preg_replace('/[\x{10000}-\x{10FFFF}]/u'"\xEF\xBF\xBD"$str);
}
?>

Pick your poison and use at your own risk!
arnoud at procurios dot nl ¶
13 years ago
Note that this function will NOT escape _ (underscore) and % (percent) signs, which have special meanings in LIKE clauses. 

As far as I know there is no function to do this, so you have to escape them yourself by adding a backslash in front of them.
zanferrari at gmail dot com ¶
4 years ago
When I submit data through Ajax I use a little function to reconvert the encoded chars to their original value. After that I do the escaping. Here the function:

   function my_htmlentities($input){
       $string = htmlentities($input,ENT_NOQUOTES,'UTF-8');
       $string = str_replace('&euro;',chr(128),$string);
       $string = html_entity_decode($string,ENT_NOQUOTES,'ISO-8859-15');
       return $string;
   }

G.Zanferrari
dave at mausner.us ¶
6 years ago
You can avoid all character escaping issues (on the PHP side) if you use prepare() and bind_param(), as an alternative to placing arbitrary string values in SQL statements.  This works because bound parameter values are NOT passed via the SQL statement syntax.
James ¶
1 year ago
To escape for the purposes of having your queries made successfully, and to prevent SQLi (SQL injection)/stored and/or reflected XSS, it's a good idea to go with the basics first, then make sure nothing gets in that can be used for SQLi or stored/reflected XSS, or even worse, loading remote images and scripts.

For example:

<?php
     
     
// Assume this is a simple comments form with a name and comment.

     
$name mysqli_real_escape_string($conn$_POST['name']);
     
$comments mysqli_real_escape_string($conn$_POST['comments']);

     
// Here is where most of the action happens.  But see note below
     // on dumping back out from the database

     // We should use the ENT_QUOTES flag second parameter...
     
$name htmlspecialchars($name);
     
$comments htmlspecialchars($comments);

     
$insert_sql "INSERT INTO tbl_comments ( c_id, c_name, c_comments ) VALUES ( DEFAULT, '" $name "', '" $comments "')";

     
$res mysqli_query($conn$insert_sql);
     if ( 
$res === false ) {
          
// Something went wrong, handle it
     
}

     
// Now output page showing comments
?>

//  Assume we're in a table with each row containing a name and comment

<?php
     
     $res 
mysqli_query($conn"SELECT c_name, c_comments FROM tbl_comments ORDER BY c_name ASC");

     if ( 
$res === false )
          
// Something went wrong

     // Or as you like...
     
while ( $row mysqli_fetch_array($resMYSQLI_BOTH) ) {
          
          
// This will output safe HTML entities if they went in
          // They will be displayed, but not interpreted
          
echo "<tr><td>" $row['c_name'] . "</td>";
          echo 
"<td>" $row['c_comments'] . "</td></tr>";

          
// BUT, if you make this mistake...
          
echo "<tr><td>" htmlspecialchars_decode($row['c_name']) . "</td>";
          echo 
"<td>" htmlspecialchars_decode($row['c_comments']) . "</td></tr>";

          
// ... then your entities will reflect back as the characters, so
          // input such as this: "><img src=x onerror=alert('xss')>
          // will display the 'xss' in an alert box in the browser.
     
}

     
mysqli_free_result($res);
     
mysqli_close($conn);
?>

In most cases, you wouldn't want to go way overboard sanitizing untrusted user input, for instance:

<?php
     $my_input 
htmlspecialcharsstrip_tags($_POST['foo']) );
?>

This will junk a lot of input you might actually want, if you're rolling your own forum or comments section and it's for web developers, for example.  On the other hand, if legitimate users are never going to enter anything other than text, never HTML tags or anything else, it's not a bad idea.

The take-away is that mysqli_real_escape_string() is not good enough, and being overly-aggressive in sanitizing input may not be what you want.

Be aware that in the above example, it will protect you from sqli (run sqlmap on all your input fields and forms to check) but it won't protect your database from being filled with junk, effectively DoS'ing your Web app in the process.

So after protecting against SQLi, even if you're behind CloudFlare and take other measures to protect your databases, there's still effectively a DoS attack that could slow down your Web App for legitimate users and make it a nightmare filled with rubbish that some poor maintainer has to clean out, if you don't take other measures.

So aside from escaping your stings, and protecting against SQLi and stored/reflected XSS, and maliciously loaded images or JS, there's also checking your input to see if it makes sense, so you don't get a database full of rubbish!

It just never ends... :-)
Anonymous ¶
2 years ago
If you wonder why (besides \, ' and ")  NUL (ASCII 0), \n, \r, and Control-Z are escaped: it is not to prevent sql injection, but to prevent your sql logfile to get unreadable.
Lawrence DOliveiro ¶
1 month ago
Note that the “like” operator requires an *additional* level of escaping for its special characters, *on top of* that performed by mysql_escape_string. But there is no built-in function for performing this escaping. Here is a function that does it:

function escape_sql_wild($s)
  /* escapes SQL pattern wildcards in s. */
  {
    $result = array();
    foreach(str_split($s) as $ch)
      {
        if ($ch == "\\" || $ch == "%" || $ch == "_")
          {
            $result[] = "\\";
          } /*if*/
        $result[] = $ch;
      } /*foreach*/
    return
        implode("", $result);
  } /*escape_sql_wild*/
anon ¶
2 years ago
if ($_SERVER['REQUEST_METHOD'] == "GET" && isset($_GET['value'])) {
    $id = trim($link->real_escape_string($_GET['value']));
    $sql = "DELETE FROM database WHERE IDItem = $id";
    if (!$res = $link->query($sql)) {
        $_SESSION['alertify'] = 'alertify.error("' . $link->error . '")';
    } else {
        $_SESSION['alertify'] = 'alertify.success("' . $value . ' was succesfully deleted")';
    }
}
kit dot lester at mail dot com ¶
4 years ago
A PHP application I'm working on has many pages which (long story) need to share a PHP API that looks after a MySQL database. Easiest way was to have the app pages AJAX to the API .PHPs.

That means having the JavaScript of the AJAX encodeURIComponent(...) relevant bits of any data to be sent via HTTP POST and GET requests - space as %20 and so on.

But the SQL also needed real_escape_string(...) of the same data.

So I had the issue of whether to do the real_escape_string *before* or *after* encodeURIComponent? in other words in the application PHP or API PHP? Do either of the encodings mangle the other?

The real_escape_string would be "cleaner" in the API, both in principle, and because it needs an instance of mysqli class and there are are unlikely to be instances in the app.

(real_escape_string needs an instance because it's not a  *static* function - I don't know why).

But I suspect that "in the API" is the mangle-avoiding place: the JavaScript encode gets undone by the HTTP call to whichever API element, then the element can safely real_escape_string what is to be put into the database.

Comments would be appreciated.
nmmm at nmmm dot nu ¶
3 years ago
Note unlike PDO string escape, MySQLi does not include apostrophes. 

So, you probably want something like this:

    function escape($s){
        $s = $this->mysqli->real_escape_string($s);
        return "'$s'";
    }


728x90

숫자 천자리마다, 즉, 아라비아 숫자의 3자리마다 콤마를 삽입하려면, number_format() 이라는 함수를 사용합니다.

number_format(숫자)
이렇게 하면, 세자리마다 쉼표가 찍힙니다.

number_format(숫자, 소수점_이하_자릿수)
이렇게 하면, 세자리마다 쉼표가 찍히고 또한, 소수점 이하 몇 자리까지 출력할 것인지 지정할 수 있습니다.

Commify: 정수/실수 세자리마다 콤마 넣기 예제


소스 파일명: example.php

<html>
<head>
<title>PHP Example</title>
</head>

<body>

<?php

  // 정수에, 천자리 마다 쉼표 넣기
  echo number_format(1234567890), "<br />\n"; # 1,234,567,890
  echo number_format(123456789), "<br />\n";  # 123,456,789
  echo number_format(12345678), "<br />\n";   # 12,345,678
  echo number_format(1000), "<br />\n";       # 1,000
  echo number_format(66), "<br />\n";         # 66



  echo "\n\n<br /><br /><br />\n\n\n";  // 줄바꿈


  // 천자리 쉼표 넣기 + 실수 소수점 이하 2자리까지 출력
  // 약간 반올림이 됨
  echo number_format(1234567890.555555, 2), "<br />\n"; # 1,234,567,890.56
  echo number_format(123456789.555555, 2), "<br />\n";  # 123,456,789.56
  echo number_format(12345678.555555, 2), "<br />\n";   # 12,345,678.56
  echo number_format(1000.555555, 2), "<br />\n";       # 1,000.56
  echo number_format(66.555555, 2), "<br />\n";         # 66.56

?>

</body>
</html>



쉼표가 들어간 숫자는 문자열이지 더 이상 숫자가 아니기에, 연산을 할 수가 없습니다.

728x90

(PHP 4, PHP 5, PHP 7)

array_push — 배열의 끝에 하나 이상의 원소를 넣는다

설명 ¶

int array_push ( array &$array , mixed $var [, mixed $... ] )

array_push()는 array를 스택으로 취급하고, array 끝에 전달되어진 변수를 넣는다. array의 길이는 집어넣은 변수의 수만큼 증가한다. 다음과 같은 효과를 갖는다:

<?php
$array
[] = $var;
?>
각 var에 대해 반복된다.

Notearray_push()를 하나의 원소를 넣는 데 사용한다면, $array[] = 을 사용하는 것이 좋습니다. 함수 호출의 오버헤드가 없기 때문입니다.

Notearray_push()에 첫번째 인수가 배열이 아니면 경고가 발생합니다. 이는 새 배열이 생성될 때 $var[] 동작과 다릅니다.

인수 ¶

array

입력 배열.

var

넣을 값.

반환값 ¶

배열에 새로 추가된 원소의 수를 반환한다.

예제 ¶

Example #1 array_push() 예제

<?php
$stack 
= array("orange""banana");
array_push($stack"apple""raspberry");
print_r($stack);
?>

위 예제의 출력:

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)

참고 ¶

  • array_pop() - 배열의 마지막 원소 빼내기
  • array_push()
  • array_unshift() - 배열의 맨 앞에 하나 이상의 원소를 첨가
add a note add a note

User Contributed Notes 29 notes

Rodrigo de Aquino ¶
5 years ago
If you're going to use array_push() to insert a "$key" => "$value" pair into an array, it can be done using the following:

    $data[$key] = $value;

It is not necessary to use array_push.
bxi at apparoat dot nl ¶
9 years ago
I've done a small comparison between array_push() and the $array[] method and the $array[] seems to be a lot faster.

<?php
$array 
= array();
for (
$x 1$x <= 100000$x++)
{
    
$array[] = $x;
}
?>
takes 0.0622200965881 seconds

and

<?php
$array 
= array();
for (
$x 1$x <= 100000$x++)
{
    
array_push($array$x);
}
?>
takes 1.63195490837 seconds

so if your not making use of the return value of array_push() its better to use the $array[] way.

Hope this helps someone.
andrew at cgipro dot com ¶
12 years ago
Need a real one-liner for adding an element onto a new array name?

$emp_list_bic = $emp_list + array(c=>"ANY CLIENT");

CONTEXT...
drewdeal: this turns out to be better and easier than array_push()
patelbhadresh: great!... so u discover new idea...
drewdeal: because you can't do:   $emp_list_bic = array_push($emp_list, c=>"ANY CLIENT");
drewdeal: array_push returns a count and affects current array.. and does not support set keys!
drewdeal: yeah. My one-liner makes a new array as a derivative of the prior array
aaron dot hawley at uvm dot edu ¶
12 years ago
Skylifter notes on 20-Jan-2004 that the [] empty bracket notation does not return the array count as array_push does.  There's another difference between array_push and the recommended empty bracket notation.

Empy bracket doesn't check if a variable is an array first as array_push does.  If array_push finds that a variable isn't an array it prints a Warning message if E_ALL error reporting is on.

So array_push is safer than [], until further this is changed by the PHP developers.
mrgreen dot webpost at gmail dot com ¶
1 year ago
Rodrigo de Aquino asserted that instead of using array_push to append to an associative array you can instead just do...

        $data[$key] = $value;

...but this is actually not true. Unlike array_push and even...

        $data[] = $value;

...Rodrigo's suggestion is NOT guaranteed to append the new element to the END of the array. For instance...

        $data['one'] = 1;
        $data['two'] = 2;
        $data['three'] = 3;
        $data['four'] = 4;

...might very well result in an array that looks like this...

       [ "four" => 4, "one" => 1, "three" => 3, "two" => 2 ]

I can only assume that PHP sorts the array as elements are added to make it easier for it to find a specified element by its key later. In many cases it won't matter if the array is not stored internally in the same order you added the elements, but if, for instance, you execute a foreach on the array later, the elements may not be processed in the order you need them to be.

If you want to add elements to the END of an associative array you should use the unary array union operator (+=) instead...

       $data['one'] = 1;
       $data += [ "two" => 2 ];
       $data += [ "three" => 3 ];
       $data += [ "four" => 4 ];

You can also, of course, append more than one element at once...

       $data['one'] = 1;
       $data += [ "two" => 2, "three" => 3 ];
       $data += [ "four" => 4 ];

Note that like array_push (but unlike $array[] =) the array must exist before the unary union, which means that if you are building an array in a loop you need to declare an empty array first...

       $data = [];
       for ( $i = 1; $i < 5; $i++ ) {
              $data += [ "element$i" => $i ];
       }

...which will result in an array that looks like this...

      [ "element1" => 1, "element2" => 2, "element3" => 3, "element4" => 4 ]
willdemaine at gmail dot com ¶
9 years ago
If you're adding multiple values to an array in a loop, it's faster to use array_push than repeated [] = statements that I see all the time:

<?php
class timer
{
        private 
$start;
        private 
$end;

        public function 
timer()
        {
                
$this->start microtime(true);
        }

        public function 
Finish()
        {
                
$this->end microtime(true);
        }

        private function 
GetStart()
        {
                if (isset(
$this->start))
                        return 
$this->start;
                else
                        return 
false;
        }

        private function 
GetEnd()
        {
                if (isset(
$this->end))
                        return 
$this->end;
                else
                        return 
false;
        }

        public function 
GetDiff()
        {
                return 
$this->GetEnd() - $this->GetStart();
        }

        public function 
Reset()
        {
                
$this->start microtime(true);
        }

}

echo 
"Adding 100k elements to array with []\n\n";
$ta = array();
$test = new Timer();
for (
$i 0$i 100000$i++)
{
        
$ta[] = $i;
}
$test->Finish();
echo 
$test->GetDiff();

echo 
"\n\nAdding 100k elements to array with array_push\n\n";
$test->Reset();
for (
$i 0$i 100000$i++)
{
        
array_push($ta,$i);
}
$test->Finish();
echo 
$test->GetDiff();

echo 
"\n\nAdding 100k elements to array with [] 10 per iteration\n\n";
$test->Reset();
for (
$i 0$i 10000$i++)
{
        
$ta[] = $i;
        
$ta[] = $i;
        
$ta[] = $i;
        
$ta[] = $i;
        
$ta[] = $i;
        
$ta[] = $i;
        
$ta[] = $i;
        
$ta[] = $i;
        
$ta[] = $i;
        
$ta[] = $i;
}
$test->Finish();
echo 
$test->GetDiff();

echo 
"\n\nAdding 100k elements to array with array_push 10 per iteration\n\n";
$test->Reset();
for (
$i 0$i 10000$i++)
{
        
array_push($ta,$i,$i,$i,$i,$i,$i,$i,$i,$i,$i);
}
$test->Finish();
echo 
$test->GetDiff();
?>

Output

$ php5 arraypush.php
X-Powered-By: PHP/5.2.5
Content-type: text/html

Adding 100k elements to array with []

0.044686794281006

Adding 100k elements to array with array_push

0.072616100311279

Adding 100k elements to array with [] 10 per iteration

0.034690141677856

Adding 100k elements to array with array_push 10 per iteration

0.023932933807373
egingell at sisna dot com ¶
11 years ago
If you push an array onto the stack, PHP will add the whole array to the next element instead of adding the keys and values to the array. If this is not what you want, you're better off using array_merge() or traverse the array you're pushing on and add each element with $stack[$key] = $value.

<?php

$stack 
= array('a''b''c');
array_push($stack, array('d''e''f'));
print_r($stack);

?>
The above will output this:
Array (
  [0] => a
  [1] => b
  [2] => c
  [3] => Array (
     [0] => a
     [1] => b
     [2] => c
  )
)
kamprettos at yahoo dot com Teguh Iskanto ¶
12 years ago
Looking for a way to push data into an associative array and frustrated to know that array_push() can't do the job ? 

here's my Scenario : 
-------------------
I need to relate system command output into an associative array like these :

[sge@digital_db work]$ /usr/local/apache/htdocs/work/qhost.sh -h t1 -F | awk '{if(NR>4) print $1}' | sed  's/hl://g' 
arch=lx24-amd64
num_proc=2.000000
mem_total=3.808G
swap_total=3.907G
virtual_total=7.715G
load_avg=0.000000
load_short=0.000000
load_medium=0.000000
load_long=0.000000
mem_free=3.510G
swap_free=3.907G
virtual_free=7.417G
mem_used=305.242M
swap_used=0.000
virtual_used=305.242M
cpu=0.000000
np_load_avg=0.000000
np_load_short=0.000000
np_load_medium=0.000000
np_load_long=0.000000

how I did it :
<? php

# get into the system command output 
$assoc_cmd =`$work_dir/qhost.sh -h $host_resource -F | awk '{if(NR>4) print $1}'| sed  's/hl://g' ` ;

# split the "\n" character 
$assoc_row = explode("\n", chop($assoc_cmd));

# get the index row 
$idx_row  = count($assoc_row) - 1 ;

# initialize the associative array 
$host_res_array = array();

for ($i = 0 ; $i<= $idx_row ; $i++) 
        {       
                # get params & values 
                list($host_param,$host_val) = explode("=",$assoc_row[$i]);

                # populate / push data to assoc array 
                $host_res_array[$host_param]= $host_val ;
        }    

echo "<pre> Architecture : </pre>\n" ;
echo $host_res_array['arch'] ;
echo "<pre> Mem Total    : </pre>\n" ;
echo $host_res_array['mem_tot'];

?>

Hope this helps ! :)
aosojnik at gmail dot com ¶
8 years ago
If you want to preserve the keys in the array, use the following: 

<?php 
function array_pshift(&$array) { 
    
$keys array_keys($array); 
    
$key array_shift($keys); 
    
$element $array[$key]; 
    unset(
$array[$key]); 
    return 
$element

?>
bk at quicknet dot nl ¶
12 years ago
Add elements to an array before or after a specific index or key:

<?php

/**
* @return array
* @param array $src
* @param array $in
* @param int|string $pos
*/
function array_push_before($src,$in,$pos){
    if(
is_int($pos)) $R=array_merge(array_slice($src,0,$pos), $inarray_slice($src,$pos));
    else{
        foreach(
$src as $k=>$v){
            if(
$k==$pos)$R=array_merge($R,$in);
            
$R[$k]=$v;
        }
    }return 
$R;
}

/**
* @return array
* @param array $src
* @param array $in
* @param int|string $pos
*/
function array_push_after($src,$in,$pos){
    if(
is_int($pos)) $R=array_merge(array_slice($src,0,$pos+1), $inarray_slice($src,$pos+1));
    else{
        foreach(
$src as $k=>$v){
            
$R[$k]=$v;
            if(
$k==$pos)$R=array_merge($R,$in);
        }
    }return 
$R;
}

// Examples:

$src=array("A","B","C");
$in=array("X","Y");

var_dump(array_push_before($src,$in,1));
/* array_push_before, no-key array
array(5) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "X"
  [2]=>
  string(1) "Y"
  [3]=>
  string(1) "B"
  [4]=>
  string(1) "C"
}*/

var_dump(array_push_after($src,$in,1));
/* array_push_after, no-key array
array(5) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "B"
  [2]=>
  string(1) "X"
  [3]=>
  string(1) "Y"
  [4]=>
  string(1) "C"
}*/

$src=array('a'=>"A",'b'=>"B",'c'=>"C");
$in=array('x'=>"X",'y'=>"Y");

var_dump(array_push_before($src,$in,1));
/* array_push_before, key array, before index insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["b"]=>
  string(1) "B"
  ["c"]=>
  string(1) "C"
}*/

var_dump(array_push_before($src,$in,'b'));
/* array_push_before, key array, before key insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["b"]=>
  string(1) "B"
  ["c"]=>
  string(1) "C"
}*/

var_dump(array_push_after($src,$in,1));
/* array_push_after, key array, after index insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["b"]=>
  string(1) "B"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["c"]=>
  string(1) "C"
}*/

var_dump(array_push_after($src,$in,'b'));
/* array_push_after, key array, after key insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["b"]=>
  string(1) "B"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["c"]=>
  string(1) "C"
}*/

?>
helpmepro1 at gmail dot com ¶
9 years ago
elegant php array combinations algorithm

<?

//by Shimon Dookin

function get_combinations(&$lists,&$result,$stack=array(),$pos=0)
{
$list=$lists[$pos];
if(is_array($list))
  foreach($list as $word)
  {
   array_push($stack,$word);
   if(count($lists)==count($stack))
    $result[]=$stack;
   else
    get_combinations($lists,$result,$stack,$pos+1);
   array_pop($stack);
  }
}

$wordlists= array( array("shimon","doodkin") , array("php programmer","sql programmer","mql metatrader programmer") );

get_combinations($wordlists,$combinations);

echo '<xmp>';
print_r($combinations);

?>
gfuente at garrahan dot gov dot ar ¶
11 months ago
If the element to be pushed onto the end of array is an array you will receive the following error message: 

Unknown Error, value: [8] Array to string conversion

I tried both: (and works, but with the warning message)

            $aRol = array( $row[0], $row[1], $row[2] );
            $aRoles[] = $aRol;

and 
            array_push( $aRoles, $aRol);

The correct way:

            $cUnRol = implode("(",array( $row[0], $row[1], $row[2] ) ); 
            array_push( $aRoles, $cUnRol ); 

thanks.
colecooper2005 at icloud dot com ¶
1 year ago
When developing a pocketmine plugin, a good way to add stuff to a YAML table is

$table=$this->config->get("Table");
array_push($table, "New Value for table");
$this->config->set("Table", $table);
raat1979 at gmail dot com ¶
1 year ago
Unfortunately array_push returns the new number of items in the array
It does not give you the key of the item you just added, in numeric arrays you could do -1, you do however need to be sure that no associative key exists as that would break the assumption

It would have been better if array_push would have returned the key of the item just added like the below function
(perhaps a native variant would be a good idea...)

<?php

if(!function_exists('array_add')){
    function 
array_add(array &$array,$value /*[, $...]*/){
        
$values func_get_args();     //get all values
        
$values[0]= &$array;        //REFERENCE!
        
$org=key($array);              //where are we?
        
call_user_func_array('array_push',$values);
        
end($array);                 // move to the last item
        
$key key($array);         //get the key of the last item
        
if($org===null){
            
//was at eof, added something, move to it
            
return $key;
        }elseif(
$org<(count($array)/2)){ //somewhere in the middle +/- is fine
            
reset($array);
            while (
key($array) !== $orgnext($List);
        }else{
            while (
key($array) !== $orgprev($List);
        }
        return 
$key;
    }
}
echo 
"<pre>\n";
$pr = array('foo'=>'bar','bar'=>'foo');
echo 
"Taken array;"
print_r($pr);

echo 
"\npush 1 returns ".array_push($pr,1)."\n";
echo 
"------------------------------------\n";
$pr = array('foo'=>'bar','bar'=>'foo');
echo 
"\npush 2 returns ".array_push($pr,1,2)."\n";
echo 
"------------------------------------\n";
$pr = array('foo'=>'bar','bar'=>'foo');
echo 
"\n add 1 returns ".array_add($pr,2)."\n\n";
echo 
"------------------------------------\n";
$pr = array('foo'=>'bar','bar'=>'foo');
echo 
"\n add 2 returns ".array_add($pr,1,2)."\n\n";
echo 
"<pre/>\n\n";
?>
Outputs:
Taken array;Array
(
    [foo] => bar
    [bar] => foo
)

push 1 returns 3
------------------------------------

push 2 returns 4
------------------------------------

add 1 returns 0

------------------------------------

add 2 returns 1
golddragon007 ¶
2 years ago
I did a performance check, and I saw, if you push more than one value it can be faster the array push, that the normal $array[] version.

Case 1: $array[] = something;
Case 2: array_push($array, $value);
Case 3: array_push($array, $value1, $value2, $value3 [...]); $values are definied
Case 4: array_push($array, $value1, $value2, $value3 [...]); $values are definied, when $array is not empty
Case 5: Case1 + Case 3
Case 6: Result array contains some value (Case 4)
Case 7: Result array contains same value as the push array (Case 4)
-----------------------------------------------------------------------------------------------------------
~~~~~~~~~~~~ Case 1 ~~~~~~~~~~~~
Times: 0.0310 0.0300 0.0290 0.0340 0.0400 0.0440 0.0480 0.0550 0.0570 0.0570
Min: 0.0290
Max: 0.0570
Avg: 0.0425
~~~~~~~~~~~~ Case 2 ~~~~~~~~~~~~
Times: 0.3890 0.3850 0.3770 0.4110 0.4020 0.3980 0.4020 0.4060 0.4130 0.4200
Min: 0.3770
Max: 0.4200
Avg: 0.4003
~~~~~~~~~~~~ Case 3 ~~~~~~~~~~~~
Times: 0.0200 0.0220 0.0240 0.0340 0.0360 0.0410 0.0460 0.0500 0.0520 0.0520
Min: 0.0200
Max: 0.0520
Avg: 0.0377
~~~~~~~~~~~~ Case 4 ~~~~~~~~~~~~
Times: 0.0200 0.0250 0.0230 0.0260 0.0330 0.0390 0.0460 0.0510 0.0520 0.0520
Min: 0.0200
Max: 0.0520
Avg: 0.0367
~~~~~~~~~~~~ Case 5 ~~~~~~~~~~~~
Times: 0.0260 0.0250 0.0370 0.0360 0.0390 0.0440 0.0510 0.0520 0.0530 0.0560
Min: 0.0250
Max: 0.0560
Avg: 0.0419
~~~~~~~~~~~~ Case 6 ~~~~~~~~~~~~
Times: 0.0340 0.0280 0.0370 0.0410 0.0450 0.0480 0.0560 0.0580 0.0580 0.0570
Min: 0.0280
Max: 0.0580
Avg: 0.0462
~~~~~~~~~~~~ Case 7 ~~~~~~~~~~~~
Times: 0.0290 0.0270 0.0350 0.0410 0.0430 0.0470 0.0540 0.0540 0.0550 0.0550
Min: 0.0270
Max: 0.0550
Avg: 0.044

Tester code:
// Case 1
    $startTime = microtime(true);
    $array = array();
    for ($x = 1; $x <= 100000; $x++)
    {
        $array[] = $x;
    }
    $endTime = microtime(true);

// Case 2
    $startTime = microtime(true);
    $array = array();
    for ($x = 1; $x <= 100000; $x++)
    {
        array_push($array, $x);
    }
    $endTime = microtime(true);

// Case 3
    $result = array();
    $array2 = array(&$result)+$array;
    $startTime = microtime(true);
    call_user_func_array("array_push", $array2);
    $endTime = microtime(true);

// Case 4
    $result = array();
    for ($x = 1; $x <= 100000; $x++)
    {
        $result[] = $x;
    }
    $array2 = array(&$result)+$array;
    $startTime = microtime(true);
    call_user_func_array("array_push", $array2);
    $endTime = microtime(true);

// Case 5
    $result = array();
    $startTime = microtime(true);
    $array = array(&$result);
    for ($x = 1; $x <= 100000; $x++)
    {
        $array[] = $x;
    }
    $endTime = microtime(true);

// Case 6
    $result = array(1,2,3,4,5,6);
    $startTime = microtime(true);
    $array = array(&$result);
    for ($x = 1; $x <= 100000; $x++)
    {
        $array[] = $x;
    }
    $endTime = microtime(true);

// Case 7
    $result = array();
    for ($x = 1; $x <= 100000; $x++)
    {
        $result[] = $x;
    }
    $startTime = microtime(true);
    $array = array(&$result);
    for ($x = 1; $x <= 100000; $x++)
    {
        $array[] = $x;
    }
    $endTime = microtime(true);
flobee ¶
4 years ago
Be warned using $array "+=" array(1,2,3) or union operations (http://php.net/manual/en/language.operators.array.php)

I think it worked in the past or i havent test it good enough. :-/ 
(once it worked, once [] was faster than array_push, the past :-D ): 

php -r '$a = array(1,2); $a += array(3,4); print_r($a);'
Array (
    [0] => 1
    [1] => 2
)
php -r '$a = array(1,2); $b = array(3,4);$c = $a + $b; print_r($c);'
Array (
    [0] => 1
    [1] => 2
)
php -r '$a = array(1,2); $b = array(2=>3,3=>4);$c = $a + $b; print_r($c);'
Array (
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
Chicna ¶
5 years ago
I found a simple way to have an "array_push_array" function, without the references problem when we want to use call_user_func_array(), hope this help : 

function array_push_array(array &$array)
{
    $numArgs = func_num_args();
    if(2 > $numArgs)
    {
      trigger_error(sprintf('%s: expects at least 2 parameters, %s given', __FUNCTION__, $numArgs), E_USER_WARNING);
      return false;
    }
    
    $values = func_get_args();
    array_shift($values);
   
    foreach($values as $v)
    {
      if(is_array($v)) 
      {
        if(count($v) > 0) 
        {
          foreach($v as $w)
          {
            $array[] = $w;
          }
        }
      }
      else 
      {
        $array[] = $v;
      }
    }
    
    return count($array);
}
rarioj at gmail dot com ¶
8 years ago
This function "Returns the new number of elements in the array."

To find out the last index, use:

<?php
$count 
array_push($array$value);
$last_index array_pop(array_keys($array));
?>
wesleys at opperschaap dot net ¶
9 years ago
A function which mimics push() from perl, perl lets you push an array to an array: push(@array, @array2, @array3). This function mimics that behaviour.

<?php

function array_push_array(&$arr) {
    
$args func_get_args();
    
array_shift($args);

    if (!
is_array($arr)) {
        
trigger_error(sprintf("%s: Cannot perform push on something that isn't an array!"__FUNCTION__), E_USER_WARNING);
        return 
false;
    }

    foreach(
$args as $v) {
        if (
is_array($v)) {
            if (
count($v) > 0) {
                
array_unshift($v, &$arr);
                
call_user_func_array('array_push',  $v);
            }
        } else {
            
$arr[] = $v;
        }
    }
    return 
count($arr);
}

$arr = array(0);
$arr2  = array(6,7,8);
printf("%s\n"array_push_array($arr, array(),array(1,2,3,4,5), $arr2));
print_r($arr);

# error.. 
$arr "test";
printf("%s\n"array_push_array($arr, array(),array(1,2,3,4,5), $arr2));

?>
alexander dot williamson at gmail dot com ¶
9 years ago
This will work to solve the associative array issues:

$aValues[$key] = $value;

Where $key is a unique identifier and $value is the value to be stored. Since the $key works off a string or number, if you already have a $key with the same value as an existing $key, the element will be overwritten.

e.g.

$aValues["one"] = "value of one";
$aValues["two"] = "different value of two!";

gives:
array([one] => "value of one", [two] => "value of two");

but will be overwritten when using the same key (one):

$aValues["one"] = "value of one";
$aValues["one"] = "different value of two!";

will give:

array([one] => "different value of two!");

3686
zbde00 at hotmail dot com ¶
10 years ago
A very good function to remove a element from array 
function array_del($str,&$array)
{
    if (in_array($str,$array)==true) 
    {
    
        foreach ($array as $key=>$value)
        {
            if ($value==$str) unset($array[$key]);
        }
    }
}
Marc Bernet ¶
11 years ago
A small and basic implementation of a stack without using an array.

class node
{
        var $elem;
        var    $next;
}
class stack
{
    var $next;
    function pop()
    {
        $aux=$this->next->elem;
        $this->next=$this->next->next;
        return $aux;
    }
    function push($obj)
    {
        $nod=new node;
        $nod->elem=$obj;
        $nod->next=$this->next;
        $this->next=$nod;
    }
    function stack()
    {
        $this->next=NULL;
    }     
}
steve at webthoughts d\ot ca ¶
12 years ago
Further Modification on the array_push_associative function
1.  removes seemingly useless array_unshift function that generates php warning
2.  adds support for non-array arguments

<?
// Append associative array elements
function array_push_associative(&$arr) {
   $args = func_get_args();
   foreach ($args as $arg) {
       if (is_array($arg)) {
           foreach ($arg as $key => $value) {
               $arr[$key] = $value;
               $ret++;
           }
       }else{
           $arr[$arg] = "";
       }
   }
   return $ret;
}

$items = array("here" => "now");
$moreitems = array("this" => "that");

$theArray = array("where" => "do we go", "here" => "we are today");
echo array_push_associative($theArray, $items, $moreitems, "five") . ' is the size of $theArray.<br />';
    
echo "<pre>";
print_r($theArray);
echo "</pre>";

?>

Yields: 

4 is the size of $theArray.
Array
(
    [where] => do we go
    [here] => now
    [this] => that
    [five] => 
)
john ¶
12 years ago
A variation of kamprettos' associative array push:

// append associative array elements
function associative_push($arr, $tmp) {
  if (is_array($tmp)) {
    foreach ($tmp as $key => $value) { 
      $arr[$key] = $value;
    }
    return $arr;
  }
  return false;
}

$theArray = array();
$theArray = associative_push($theArray, $items);
ciprian dot amariei at gmail com ¶
12 years ago
regarding the speed of oneill's solution to insert a value into a non-associative array,  I've done some tests and I found that it behaves well if you have a small array and more insertions, but for a huge array and a little insersions I sugest  using this function:

function array_insert( &$array, $index, $value ) {
   $cnt = count($array);

   for( $i = $cnt-1; $i >= $index; --$i ) {
       $array[ $i + 1 ] = $array[ $i ];
   }
   $array[$index] = $value;
}

or if you are a speed adicted programmer (same situation: big array, few insertions) use this:

array_splice ( $array, $offset, 0, $item );

item may also be an array of values ;).
Phil Davies ¶
12 years ago
As someone pointed out the array_push() function returns the count of the array not the key of the new element. As it was the latter function i required i wrote this very simple replacement.

function array_push2(&$array,$object,$key=null){
    $keys = array_keys($array);
    rsort($keys);
    $newkey = ($key==null)?$keys[0]+1:$key;
    $array[$newkey] = $object;
    return $newkey;
}
bart at framers dot nl ¶
16 years ago
Array_push also works fine with multidimensional arrays. Just make sure the element is defined as an array first. 

<?php 
$array
["element"][$element]["element"] = array(); 
array_push ($array["element"][$element]["element"], "banana"); 
?>
yuri ¶
6 years ago
If you want to put an element to a specific position in an array, try this function.

<?php

function array_put_to_position(&$array$object$position$name null)
{
        
$count 0;
        
$return = array();
        foreach (
$array as $k => $v
        {   
                
// insert new object
                
if ($count == $position)
                {   
                        if (!
$name$name $count;
                        
$return[$name] = $object;
                        
$inserted true;
                }   
                
// insert old object
                
$return[$k] = $v
                
$count++;
        }   
        if (!
$name$name $count;
        if (!
$inserted$return[$name];
        
$array $return;
        return 
$array;
}
?>

Example :

<?php
$a 
= array(
'a' => 'A',
'b' => 'B',
'c' => 'C',
);
            
print_r($a);
array_put_to_position($a'G'2'g');
print_r($a);

/*
Array
(
    [a] => A
    [b] => B
    [c] => C
)
Array
(
    [a] => A
    [b] => B
    [g] => G
    [c] => C
)
*/
?>
oneill at c dot dk ¶
12 years ago
To insert a value into a non-associative array, I find this simple function does the trick:

function insert_in_array_pos($array, $pos, $value)
{
  $result = array_merge(array_slice($array, 0 , $pos), array($value), array_slice($array,  $pos));
  return $result;
}

Seems an awful lot simpler than the iterative solutions given above...


+ Recent posts