Sub S7v7n
Sub S7v7n

Reputation: 21

How to find key in array?

I have a large array [3744] (read in from file). Array key always changes, and does not have the same value.

First run Blu-Ray:

Output 0: [55] => TINFO: 0,10,0, "36.9 GB"

Second DVD:

Output 1: [135] => TINFO: 0,10,0, "5.7 GB"

but part of the edition is "TINFO: 0,10,0," always the same.

How can I search my array for "TINFO: 0,10,0," to get the array key, would be happy?

<?php 
   $size=shell_exec("sudo makemkvcon -r info dev:/dev/sr0 | grep -i 'TINFO:0,10,0,'");
   $size=substr($size, 14, -2);
?>

Output is perfect, but with multiple queries it takes a long time, so I've saved the entire output in file.

<?php 
    $BD_Info_array = file("../BD_Info");
    $key = array_search('TINFO:0,10,0,', $BD_Info_array);
    echo $BD_Info_array[$key];
?>

Here I get the first line of the file, it's not what I want.

MSG:1005,0,1,"MakeMKV v1.14.3 linux(x64-release) started","%1 started","MakeMKV v1.14.3 linux(x64-release)"

Upvotes: 0

Views: 115

Answers (2)

Sub S7v7n
Sub S7v7n

Reputation: 21

I solved it that way:

/// get size
$lines = file('../BD_Info');
$searchstr = 'TINFO:0,10,0,';

foreach ($lines as $line) {
    if(strpos($line, $searchstr) !== false) {
        $size[] = $line;
    }
}

echo $size[0];                  //// OUTPUT > TINFO:0,10,0,"36.9 GB" 
echo substr($size[0], 14, -2);  //// OUTPUT > 36.9 GB

Upvotes: 0

Garrett Albright
Garrett Albright

Reputation: 2841

You're getting the first line of the file because array_search() returns boolean FALSE if it can't find what you're looking for in the array, so $key is being set to FALSE. Then, when you do echo $BD_Info_array[$key];, $key is being interpreted as the integer 0, so you basically get the same result as doing echo $BD_Info_array[0].

You should use the identity operator === to check if $key is really FALSE before printing the line:

if ($key === FALSE) {
  echo "Line not found!";
}
else {
  echo $BD_Info_array[$key];
}

As for why array_search() isn't finding your line, it works differently than grep. It will look for an item in the array that has that exact value as the value. If you want your PHP code to just find a line which contains that substring, you'll want to iterate through the array created by file() and use strpos() to find the line - but note that strpos() also returns FALSE if it doesn't find a match, and a numerical value (which may be 0 and therefore evaluate to FALSE) if it does.

Upvotes: 1

Related Questions