Подробное руководство по php-массивам

How to create an Array in PHP?

Single dimensional array

<?php

$animals = array(“Lion”, “Tiger”, “Wolf”);
$arrLength = count($animals);

// loop through the array
for($i = 0; $i < $arrLength; $i++) {
    echo $animals;
    echo "</ br>";
}

?>

Associative array

<?php

$animals = array("Lion"=>"Wild", "Sheep"=>"Domestic", "Tiger"=>"Wild");

// loop through associative array and get key value pairs
foreach($animals as $key => $value) {
    echo "Key=" . $key . ", Value=" . $value;
    echo "</br>";
}

?>

Two dimensional array

<?php

// two-dimensional array definition
$animals = array
  (
  array("Lion","Wild",8),
  array("Sheep","Domestic",12),
  array("Tiger","Wild",20)
  );

// two-dimensional array iteration
for ($row = 0; $row < 3; $row++) {
  echo "<p>Row number $row</p>";
  echo "<ul>";
  for ($col = 0; $col < 3; $col++) {
    echo "<li>".$animals."</li>";
  }
  echo "</ul>";
}

?>

Via loop

<?php

$animals = array();
for ($i = 0; $i < $count; $i++) {
    $animals = array
        ( $animalName
        , $animalType
        );
}

?>

Three dimensional array

<?php
$threeDArray = array( 
    array( 
        array("Lion", "Tiger"), 
        array("Sheep", "Dog"), 
    ), 
    array( 
        array("Apple", "Orange"), 
        array("Tomato", "Potato"), 
    ), 
); 
?>

5 последних уроков рубрики «PHP»

Когда речь идёт о безопасности веб-сайта, то фраза «фильтруйте всё, экранируйте всё» всегда будет актуальна. Сегодня поговорим о фильтрации данных.

Обеспечение безопасности веб-сайта — это не только защита от SQL инъекций, но и протекция от межсайтового скриптинга (XSS), межсайтовой подделки запросов (CSRF) и от других видов атак

В частности, вам нужно очень осторожно подходить к формированию HTML, CSS и JavaScript кода.

Expressive 2 поддерживает возможность подключения других ZF компонент по специальной схеме. Не всем нравится данное решение

В этой статье мы расскажем как улучшили процесс подключение нескольких модулей.

Предположим, что вам необходимо отправить какую-то информацию в Google Analytics из серверного скрипта. Как это сделать. Ответ в этой заметке.

Подборка PHP песочниц
Подборка из нескольких видов PHP песочниц. На некоторых вы в режиме online сможете потестить свой код, но есть так же решения, которые можно внедрить на свой сайт.

Finding intersection, difference and union of arrays

PHP has wide array of in-built functions for handling arrays. Intersection, difference and union are performed quite regularly when using arrays. PHP has got good set of functions in-built to handle these operations.

Array intersection

PHP array_intersect function is used to find intersection between arrays. This function can accept multiple arguments to compare. After comparison, this function returns an array of intersecting elements that are present in all the argument arrays.

Syntax:

array_intersect($input_array1,$input_array2,$input_array3...)

Array intersection example

In this example, we are going to pass four arrays as parameters.

<?php
$soft_toys = array("Baby Pillow", "Teddy Bear", "Chicklings");
$baby_toys = array("Toy phone", "Baby Pillow", "Lighting Ball", "Teddy Bear");
$gift_items = array("Coloring Fun", "Baby Pillow", "Barbies", "Teddy Bear");
$kids_bedroom_set = array("Teddy Bear", "Baby Pillow", "Night Lamp","Kids Bed");
$arrayIntersect = array_intersect($soft_toys, $baby_toys, $gift_items, $kids_bedroom_set);
print "<PRE>";
print_r($arrayIntersect);
print "</PRE>";
?>

This program prints resultant array containing values that are present in all the four input arrays. The output is,

Array(
     => Baby Pillow
     => Teddy Bear
)

Other Array intersection functions in PHP

PHP includes more variety of functions to calculate intersection of elements among input arrays.

  • – returns intersecting elements with respect to the keys.
  • – returns intersecting elements with respect to keys and values.
  • – returns intersecting elements on the basis of custom function by providing an algorithm for the intersection.

Array difference

By using PHP array difference functions, we can find differences between arrays with respect to their keys or values.

  • array_diff
  • array_diff_key
  • array_diff_assoc

Array differences can also be found, based on the index check by using the custom made functions. They are used as a callback.

  • array_diff_ukey
  • array_diff_uassoc

The list goes on. By comparing their entries with the use of user-defined callback functions.

  • array_udiff
  • array_udiff_assoc
  • array_udiff_uassoc

array_diff

It accepts at least two arrays, but, maximum in any number of arrays, as its arguments, thereby, the elements from the first array will be compared with the rest of the array elements.

array_diff_assoc

This function is used to compare the values between given arrays, by considering the key index associated with these values.

Array difference example

<?php
$array_from = array("fruit1" => "apple", "fruit2" => "grapes","friut3" =>"banana");
$array_against = array("fruit1" => "orange", "fruit2" => "grapes","friut4" => "banana");
$value_differences = array_diff($array_from, $array_against);
$key_differences = array_diff_key($array_from, $array_against);
$assoc_index_differences = array_diff_assoc($array_from, $array_against);
print "<PRE>";
print_r($value_differences);
print_r($key_differences);
print_r($assoc_index_differences);
print "</PRE>";
?>

Array difference example’s output below:

Array
(
 => apple
)
Array
(
 => banana
)
Array
(
 => apple
 => banana
)

PHP Array difference with callback – closures

It is possible to define your own custom logic to find difference between arrays. User-defined functions can be passed for callback.

Passing functions as argument is a cool feature in PHP. They are called anonymous functions and implemented using closures.

  • array_diff_ukey , array_diff_uassoc for key and index based differences.
  • array_udiff , array_udiff_assoc for value based array difference.
  • array_udiff_uassoc used to perform both array value and key index comparison.

Creating variables from array keys

PHP has a function named extract to create variables using array keys. It creates PHP variables with the name of each array keys. It uses an associative array as input argument.

extract

This function accepts three arguments as listed below.

  • $input_array – Associative array from which the keys are converted into PHP variables.
  • $extract_type

    EXTR_OVERWRITE, EXTR_SKIP, EXTR_IF_EXISTS, EXTR_REFS are the options.

    – Defines options to create a new variable or overwrite existing variables.

  • $variable_prefix – String to prefix with the variable name to be created.

PHP extract example

<?php
$partA = "";
$partB = "";
$input_array = array("partA" => "Stories","partB" => "Rhymes", "partC" => "Concepts");
extract($input_array,EXTR_OVERWRITE);
print '$partA='. $partA . '<br/>';
print '$partB='. $partB . '<br/>';
print '$partC='. $partC . '<br/>';
?>

Caution on using extract

You should not use extract on user input data. If you do so, it may cause security concerns. Do not use this function, unless otherwise you know what you are doing!

Работаем с массивами как профи

Поистине крутые вещи начинают происходить, когда мы комбинируем несколько вышеупомянутых функций. К примеру мы можем убрать из массива все пустые значения, вызвав и :

$values = ;

$words = array_filter(array_map('trim', $values));
print_r($words); // 

Чтобы получить идентификаторы и названия объектов моделей достаточно вызывать и :

$models = ;

$id_to_title = array_combine(
    array_column($models, 'id'),
    array_column($models, 'title')
);

Подсчёт трёх самых часто используемых элемента массива можно осуществить вызовом , и :

$letters = ;

$values = array_count_values($letters); // get key to count array
arsort($values); // sort descending preserving key
$top = array_slice($values, 0, 3); // get top 3

print_r($top);
// Array
// (
// 	 => 5
// 	 => 4
// 	 => 2
// )

Комбинация функций и позволит с лёгкостью подсчитать сумму товаров в корзине:

$order = ,
    ,
    ,
];

$sum = array_sum(array_map(function($product_row) {
    return $product_row * $product_row;
}, $order));

print_r($sum); // 250

Recursive count() example

See the following code.

<?php

// app.php

$food = array('fruits' => array('orange', 'banana', 'apple'),
              'veggie' => array('carrot', 'collard', 'pea'));

echo count($food, COUNT_RECURSIVE);

Now run the app.php file and see the output.

In the above code, we have passed the COUNT_RECURSIVE parameter that is why it counts every item in the array as well as sub-arrays that is why the total 8 items and it returns 8.

If you do not pass the COUNT_RECURSIVE, then it will return 2 items.

<?php

// app.php

$food = array('fruits' => array('orange', 'banana', 'apple'),
              'veggie' => array('carrot', 'collard', 'pea'));

echo count($food);

See the output.

If you want to run through the large arrays then don’t use the count() function in the loops, its an over the head in performance,  copy the count() value into a variable and use that value in loops for better performance.

See the following code example.

// Bad approach 

for($i=0;$i<count($arr);$i++) 
{ 
    // calculations 
} 

// Good approach 

$arr_length = count($arr); 
for($i=0;$i<$arr_length;$i++) 
{ 
    // calculations 
}

The following function of one line to find a number of items that are not arrays, recursively.

function count_elt($array, &$count=0){
  foreach($array as $v) if(is_array($v)) count_elt($v,$count); else ++$count;
  return $count;
}

When it comes to multidimensional arrays, and you do not want all levels of the array tree. The following function is beneficial.

<?php 

// $limit is set to the number of recursions

function count_recursive ($array, $limit) { 
    $count = 0; 
    foreach ($array as $id => $_array) { 
        if (is_array ($_array) && $limit > 0) { 
            $count += count_recursive ($_array, $limit - 1); 
        } else { 
            $count += 1; 
        } 
    } 
    return $count; 
} 
?>

Finally, PHP Array Count Example | PHP count() Function Tutorial is over.

How to find the size of a PHP Array?

You can use function to find the size of an array. is an alias of the function .

You might think what is the big deal with count function. If you are a beginner, you will definitely learn something new, so read on and do not skip this. Also remember to check the example script.

count

The syntax of PHP  function is,

count(var array_variable, mode)

If the value of is not set or having an empty array, then will return 0. And, if it is not an array, then count will return 1. In PHP version 7 onwards, you will get a warning.

So whenever you need to check if a PHP array is empty, you need to use the count function. Ensure that you pass array to the count function.

<?php
if (count($array) > 0) {
    echo "array has elements";
}
else {
    echo "array is empty";
}
?>

The argument is optional and it specifies the mode of operation to be used in calculating array length. Possible options are,

  • COUNT_NORMAL – will return the length of an array in depth 0. This is the default.
  • COUNT_RECURSIVE – for recursive count operation, till it reaches depth n. This recursive call will be continued infinitely, till it reaches depth n or the program execution time limit is elapsed.

Example: PHP count() with mode option

Following script is an example for function to calculate a number of elements available to a depth level. Let us use a two-dimensional array so that we can specify the mode depth.

$toys = array(array("name"=>"Mechanical Cars","category"=>"pull back"),
array("name"=>"Jigsaw","category"=>"puzzles"),
array("name"=>"HiTech Cars","category"=>"remote"),
array("name"=>"Teddy Bears","category"=>"soft"),
array("name"=>"Baby pillow","category"=>"soft"),
array("name"=>"Chinese Checker","category"=>"puzzles"),
array("name"=>"Jumbo Helicopter","category"=>"remote"));

Now, we can invoke function by passing different possible options.

$array_length = count($toys,COUNT_NORMAL);
//(OR) 
$array_length = count($toys);
$array_length = count($toys,COUNT_RECURSIVE);
print "<pre>";
print_r($array_length);
print "</pre>";

In the above PHP code, the count() is invoked with normal, default and recursive mode. Returned values are stored into an array named, $array_length, by specifying the appropriate name indices.

Following is the output of this program.

Array
(
     => 7
     => 7
     => 21
)

sizeof

This function is an alias of PHP function. It accepts the same set of arguments as like as .

We can replace the with in the above PHP code to compare the results of both functions which will be same for both functions calls.

Alias functions in PHP are preserved for providing backward compatibility. If you are writing a new program it is better not to go with the alias functions as there is a chance to deprecate it in the future.

PHP Array Count Example

PHP count() function count all elements in an array or something in an object. See the following syntax.

count(array,mode);

The array parameter is required, and it returns the number of elements in the array.

The mode parameter is Optional. Specifies the mode. Possible values:

  1. 0 – Default. Does not count all elements of multidimensional arrays
  2. 1 – Counts the array recursively (counts all the elements of multidimensional arrays)

See the following code example of PHP count() method.

<?php

// app.php

$brands = ;
echo count($brands);

See the below output.

In the above code, we have four items in the array. So, it will return 4 in the output.

The count() function may return 0 for the variable which is not set, but it may also return 0 for the variable that has been initialized with the empty array.

The isset() function should be used to test whether the variable is set or not.

Математические операции

С помощью функции array_sum() можно посчитать сумму элементов массива; array_product() перемножит все значения; array_reduce() позволит применить свою собственную формулу:

$numbers = ;

echo(array_sum($numbers)); // 15
echo(array_product($numbers)); // 120

echo(array_reduce($numbers, function($carry, $item) {
    return $carry ? $carry / $item : 1;
})); // 0.0083 = 1/2/3/4/5

Функция array_count_values() поможет посчитать количество всех уникальных значений массива:

$things = ;
$values = array_count_values($things);

print_r($values);

// Array
// (
// 	 => 2
// 	 => 1
// 	 => 3
// )

How to convert a string to an array in PHP?

You can use the built-in function explode to convert a string to an array. function is deprecated and so do not use it for creating an array based on a string.

PHP Explode

is to split the string into an array of elements based on a given separator. explode accepts separator and a string as its argument.

$input_string = "implode|join|concatenate";
$str_explode = "|";
$exploded_array = explode($str_explode,$input_string );
echo "<pre>";
print_r($exploded_array); 
echo "</pre>";

This example code accepts the resultant string data of implode example we just saw above. Explode splits string data based on the argument separator “|”. The output is,

Array
(    => implode
     => join
     => concatenate
)

Explode within Limit

PHP explode() accepts a third optional argument to set target length or boundary for performing explode operation. will take entire string as default if is not specified.

$exploded_array = explode($str_explode,$input_string,2);

this will return,

Array
(    => implode
     => join|concatenate
)

Frequently used built-in Array functions

Let us see some of the widely used PHP array functions with PHP code snippet examples.

range

PHP function is used get the array of elements in the range between the start and end parameters. The range can be a numeric or alphabet. The following code shows how to get the array of alphabets that exists between “e” and “i”.

$character_array = range('e','i'); //  returns array('e','f','g','h','i');

reset

The function is used to reset the position of the array pointer. It requires the array variable as its argument, to move the array pointer to its original position.

$character_array = range('e','i'); //  returns array('e','f','g','h','i');
print next($character_array); // prints f
print next($character_array); // prints g
reset($character_array);
print current($character_array); // prints the first element 'e' after reset

array_slice

It is used to get the sub-array from the given input array. It accepts the input array, starting position as offset and the length of the sub array.

The length parameter is optional. If it is not specified, the length of the input array will be taken by default. The fourth argument is to preserve keys by avoiding the default index reordering behavior.

$color_array = array("Red","Blue","Green","Yellow","Brown"); 
sliced_array = array_slice($color_array,1,3);//  now the sliced array will be array("Blue","Green","Yellow")

array_splice

This function is similar to array_slice and it can also replace the removed elements with the new set of elements. The length of the removed set and new array should be same.

$character_array =  array('e','f','g','h','i');
$number_array = array('1','2','3');
$changed_array = array_splice($character_array,1,3,$number_array); // will hold the element like: array('e','1','2','3','i');

array_chunk

is used to break an array into the specified length of chunks.

$character_array = array('e','f','g','h','i');
$chunks = array_chunk($character_array,2);
//$chunks will be as follows
/*
Array (
 => Array (
 => e
 => f
)
 => Array (
 => g
 => h
)
 => Array (
 => i
)
)
*/

merge

function, is for joining one or more arrays into a single array.

$color_array1 = array("Red","Blue","Green");
$color_array2 = array("Yellow","Brown");
// returns array("Red","Blue","Green","Yellow","Brown");
$color_array = array_merge($color_array1,$color_array2);

array_key_exists

This function is used to check whether the given key exists in the array or not. This function takes a key element and the input array as arguments.

array_keys, array_values

These two functions will return the keys and values of an input array, respectively. The following code shows the usage method of these functions and the resultant array of keys and values.

$student_array = array("name"=>"Martin","mark"=>"90","grade"=>"A");
$key_array = array_keys($student_array) // returns array("name","mark","grade")
$value_array = array_values($student_array) // returns array("Martin","90","A")

array_push, array_pop, array_shift, array_unshift

is used to push values into an array. Using this function, a new element will be added to the end of a given input array.

The is used to get the last element of the array.

The  and the methods are as similar as and . But, the insert and retrieve operations are performed at the starting position of the array.

extract, compact

The is used to convert the variable into an array, whereas, the is used to extract an array and convert the element of that array as variables.

The example shows it as follows. The second and third argument of extract() is optional. It is used to add a prefix to the variable name.

$student_array = array("name"=>"Martin","mark"=>"90","grade"=>"A");
extract($student_array,EXTR_PREFIX_ALL,"student"); 
echo $student_name . "-" . $student_mark . "(" . $student_grade . ")"; // prints as Martin - 90(A)
$compact_array = compact("student_name","student_mark","student_grade"); // will form an array
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector