Programming Articles - Page 2038 of 3363

How can I most efficiently check for the existence of a single value in an array of thousands of values in PHP?

AmitDiwan
Updated on 06-Apr-2020 08:28:04

118 Views

A quick way of doing this has been shown below −if (array_flip($set)[$value] !== null) {    echo "something"; //take some action }To customize the number of keys, the function can be customized in the below manner −function array_keys_exists(array $keys, array $arr) {    return !array_diff_key(array_flip($keys), $arr); }

Send multiple data with ajax in PHP

AmitDiwan
Updated on 06-Apr-2020 08:26:11

6K+ Views

Data can be sent through JSON or via normal POST. Following is an example showing data sent through JSON −var value_1 = 1; var value_2 = 2; var value_3 = 3; $.ajax({    type: "POST",    contentType: "application/json; charset=utf-8",    url: "your_url_goes_here",    data: { data_1: value_1, data_2: value_2, data_3: value_3 },    success: function (result) {       // perform operations here    } });With normal post, the below code can be used −$.ajax({    type: "POST",    url: $('form').attr("action"),    data: $('#form0').serialize(),    success: function (result) {       // perform operations here    } });An ... Read More

Get unix timestamp from string without setting default timezone in PHP

AmitDiwan
Updated on 06-Apr-2020 08:23:28

592 Views

String has a time zone, and there is usually no need to set a default time zone. But when it needs to be printed, the default time zone can be set explicitly. Below is the code to do the same −Default timezoneExample Live Demoecho date_default_timezone_get();OutputThis will produce the following output −UTCWhen timezone is specifiedExample Live Demoecho date("Y-m-d H:i:s",strtotime("1/1/2020 00:00:00 America/Los_Angeles"));OutputThis will produce the following output −2020-01-01 08:00:00 Another way of specifying timezoneExample Live Demoecho date("Y-m-d H:i:s",strtotime("1/1/2020 00:00:00"));OutputThis will produce the following output −2020-01-01 00:00:00

How to effectively hide Href From a Link in PHP?

AmitDiwan
Updated on 06-Apr-2020 08:20:48

813 Views

This is not possible. A href can’t be hidden from a link. But the files can be rewritten and the request URL can be changed to look like this − name.php/5001Other than this, a post request can be used in the below way − Go This will expose a single button in the browser.

PHP script to get all keys from an array that starts with a certain string

AmitDiwan
Updated on 06-Apr-2020 08:18:02

1K+ Views

Method 1$arr_main_array = array('test_val' => 123, 'other-value' => 456, 'test_result' => 789); foreach($arr_main_array as $key => $value){    $exp_key = explode('-', $key);    if($exp_key[0] == 'test'){       $arr_result[] = $value;    } } if(isset($arr_result)){    print_r($arr_result); }Method 2A functional approach An array_filter_key type of function is taken, and applied to the array elements $array = array_filter_key($array, function($key) {    return strpos($key, 'foo-') === 0; });Method 3A procedural approach −$val_1 = array(); foreach ($array as $key => $value) {    if (strpos($key, 'foo-') === 0) {       $val_1[$key] = $value;    } }Method 4A procedural approach using ... Read More

How to resize image in PHP?

AmitDiwan
Updated on 06-Apr-2020 07:55:41

5K+ Views

Images can be resized using ImageMagick or GD functions. If GD’s functions are used, the size of the image file is also reduced when raw digital camera images are sampled. We will see how GD can be used to resize an image in the below code.function image_resize($file_name, $width, $height, $crop=FALSE) {    list($wid, $ht) = getimagesize($file_name);    $r = $wid / $ht;    if ($crop) {       if ($wid > $ht) {          $wid = ceil($wid-($width*abs($r-$width/$height)));       } else {          $ht = ceil($ht-($ht*abs($r-$w/$h)));       }     ... Read More

Sort multidimensional array by multiple keys in PHP

AmitDiwan
Updated on 06-Apr-2020 07:53:22

3K+ Views

The array_multisort function can be used to sort a multidimensional array based on multiple keys −Example$my_list = array(    array('ID' => 1, 'title' => 'data one', 'event_type' => 'one'),    array('ID' => 2, 'title' => 'data two', 'event_type' => 'zero'),    array('ID' => 3, 'title' => 'data three', 'event_type' => 'one'),    array('ID' => 4, 'title' => 'data four', 'event_type' => 'zero') ); # The list of sorted columns and their data can be obtained. This will be passed to the array_multisort function. $sort = array(); foreach($my_list as $k=>$v) {    $sort['title'][$k] = $v['title'];    $sort['event_type'][$k] = $v['event_type']; } # ... Read More

Convert Dashes to CamelCase in PHP

AmitDiwan
Updated on 06-Apr-2020 07:38:16

1K+ Views

Following is the code to convert dashes to CamelCase in PHP −Sample input − this-is-a-test-stringSample output − thisIsATestStringNote − There is no need to use regex or callbacks. It can be achieved using ucwords.function dashToCamelCase($string, $capitalizeFirstCharacter = false) {    $str = str_replace(' ', '', ucwords(str_replace('-', ' ', $string)));    if (!$capitalizeFirstCharacter) {       $str[0] = strtolower($str[0]);    }    return $str; } echo dashToCamelCase('this-is-a-string');For PHP version>=5.3, the below code can be used −function dashToCamelCase($string, $capitalizeFirstCharacter = false) {    $str = str_replace('-', '', ucwords($string, '-'));    if (!$capitalizeFirstCharacter) {       $str = lcfirst($str);    } ... Read More

How to upload multiple files and store them in a folder with PHP?

AmitDiwan
Updated on 06-Apr-2020 07:36:51

18K+ Views

Below are the steps to upload multiple files and store them in a folder −Input name must be defined as an array i.e. name="inputName[]"Input element should have multiple="multiple" or just multipleIn the PHP file, use the syntax "$_FILES['inputName']['param'][index]"Empty file names and paths have to be checked for since the array might contain empty strings. To resolve this, use array_filter() before count.Below is a demonstration of the code −HTMLPHP$files = array_filter($_FILES['upload']['name']); //Use something similar before processing files. // Count the number of uploaded files in array $total_count = count($_FILES['upload']['name']); // Loop through every file for( $i=0 ; $i < $total_count ; ... Read More

Extract a property from an array of objects in PHP

AmitDiwan
Updated on 06-Apr-2020 07:34:36

4K+ Views

Given the below code, the task is to extract the ID of the my_object variable −Example$my_object = Array ( [0] => stdClass Object    (       [id] => 12    ),    [1] => stdClass Object    (       [id] => 33    ),    [2] => stdClass Object    (       [id] => 59    ) )The array_map function can be used for older versions of PHP. Below is a demonstration of the same.$object_id = array_map(create_function('$o', 'return $o->id;'), $objects);For PHP version 5.5 or higher, the array_column function could be used. Below is a demonstration of the same −$object_id = array_column($my_object, 'id');OutputThis will produce the following output −[12, 33, 59]

Advertisements