sediea
sediea

Reputation: 1

Can the array_intersect be used like this

$length =count($k);
$name=array();
$j=$k[0];
$out =preg_grep("[".$j."]",$database);
array_push($name,$out);
for($x=1;$x<$length;$x++)
{
    $j = $k[$x];
    $out = preg_grep("[" . $j . "]", $name);
    $name = array_intersect($out, $name);
}

i want to replace$namewith$outby computing the intersection of this two arrays,but it shows

Warning: Array to string conversion


i post all my code there now.what i want to do was found people's name include all the alphabets the$keys lent.

<?php
$keys ='aed';
$database = file('database.txt');//there same people's name in it,
$k = str_split($keys);
$length =count($k);
$name=array();
$j=$k[0];
$out =preg_grep("[".$j."]",$database);
array_push($name,$out);
for($x=1;$x<$length;$x++)
{
    $j = $k[$x];
    $out = preg_grep("[" . $j . "]", $name);
    $name = array_intersect($out, $name);
}
echo '<pre>';
var_dump($name);
echo '</pre>';

Upvotes: 0

Views: 126

Answers (1)

steven7mwesigwa
steven7mwesigwa

Reputation: 6720

Sample database.txt file.

John
peter
Eel
Audy
Sammy
dawn
Alpine
Fernando
Alfred

Error: Stack trace.

# Stack trace.

C:\xampp\php\php.exe C:\Users\Ivan\AppData\Roaming\JetBrains\PhpStorm2021.2\scratches\scratch_40.php
PHP Warning:  Array to string conversion in C:\Users\Ivan\AppData\Roaming\JetBrains\PhpStorm2021.2\scratches\scratch_40.php on line 13
PHP Stack trace:
PHP   1. {main}() C:\Users\Ivan\AppData\Roaming\JetBrains\PhpStorm2021.2\scratches\scratch_40.php:0
PHP   2. preg_grep($pattern = '[e]', $array = [0 => [4 => 'Sammy\n', 5 => 'dawn\n']]) C:\Users\Ivan\AppData\Roaming\JetBrains\PhpStorm2021.2\scratches\scratch_40.php:13
# ...

Line 13: Leading to the error/warning at hand.

// ...
$out = preg_grep("[" . $j . "]", $name);
// ...

Looking at the error stack trace, the variable $name is an array of array, yet preg_grep() doesn't work on array values that are arrays themselves. I.e:

// return all array elements
// containing floating point numbers.
$array = ["Roy", "Zoom", 6, 5.7, 345, 1.2, []]; // Last array value is an array itself.
$fl_array = preg_grep("/^(\d+)?\.\d+$/", $array);
var_export($fl_array); // Throws: PHP Warning:  Array to string conversion...

what i want to do was found people's name include all the alphabets the$keys lent.

This requirement can be fulfilled in a much shorter way:

$keys = 'aed';
$databaseNames = file('database.txt');//there same people's name in it,
$pattern = str_split($keys);

array_walk($pattern, function (&$v, $k) {
    $v = "(?=.*" . $v . ")";
});

$result = preg_grep("/" . implode($pattern) . "/i", $databaseNames);

var_export($result);

// Output.
/*array (
    7 => 'Fernando',
    8 => 'Alfred',
)*/

Upvotes: 1

Related Questions