-1

My data was save in database in serialize format. I want to unserialize data that i get from select query then compute length of this and return index of some value in data. result of unserialize data is like

Array ( [0] => [1] => 3445 [2] => [3] => 3446 [4] => [5] => 3452 [6] => [7] => 3530 [8] => 3555 )

how can I compute array length and return index of special value? in my code length of value false number

$str = $row->cur;
$str_len=unserialize($str);
print_r($str_len);
$str_length=count($str_len);
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • I think you're just looking for array_search. See https://www.php.net/manual/en/function.array-search.php – beltouche Nov 15 '20 at 17:20

1 Answers1

0

Use count($arr) to compute array length of array $arr, and array_search($needle, $arr) to get the index of a value ($needle) you're looking for in the source array ($arr).

<?php

$arr = ['', 3445, '', 3446, '', 3452, '', 3530, 3555,];

$arrayLen = count($arr);
echo 'array length : ' . $arrayLen; // 9
echo PHP_EOL;

// return index of value
$needle = 3452;
$index = array_search($needle, $arr);
echo 'found value ' . $needle . ' at index : ' . $index; // found value 3452 at index 5

Update: If you want to count only non-empty values in your array, you can use array_filter():

// Count only non empty array entries
$arrNonEmpty = array_filter($arr, function($element) { return !empty($element); });
$count = count($arrNonEmpty);

array_filter() invokes a callback function (an anonymous function in this case) to filter and return all non-empty values in the source array.

Updated: You can play with the code here

jibsteroos
  • 1,366
  • 2
  • 7
  • 13
  • thank you, But this code calculate count of array that is empty. how can i show result 5 instead of 9 for count array? – Sara Shafahi Nov 19 '20 at 03:33
  • 1
    @mickmackusa thanks, re. the answer, I was actually not satisfied with it, and didn't have time to refactor. keep up the good work! – jibsteroos Nov 20 '20 at 08:39